php 判断数组键值是否存在 array_key_exists() 与 isset()

php使用array_key_exists() 与 isset() 来判断数组中的某个键值是否存在。一起看下使用方法:

array_key_exists

(PHP 4 >= 4.0.7, PHP 5)

array_key_exists — 检查给定的键名或索引是否存在于数组中
说明

bool array_key_exists ( mixed $key , array $search )

array_key_exists() 在给定的 key 存在于数组中时返回 TRUE。key 可以是任何能作为数组索引的值。array_key_exists() 也可用于对象。
Example #1 array_key_exists() 例子
<?php
$search_array = array(‘first’ => 1, ‘second’ => 4);
if (array_key_exists(‘first’, $search_array)) {
echo “The ‘first’ element is in the array”;
}
?>

Note: 在 PHP 4.0.6 中本函数名为 key_exists()。
Example #2 array_key_exists() 与 isset() 对比
isset() 对于数组中为 NULL 的值不会返回 TRUE,而 array_key_exists() 会。
<?php
$search_array = array(‘first’ => null, ‘second’ => 4);

// returns false
isset($search_array[‘first’]);

// returns true
array_key_exists(‘first’, $search_array);
?>

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注

您可以使用这些HTML标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>