array_key_exists

(PHP 4 >= 4.1.0, PHP 5)

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

说明

bool array_key_exists ( mixed key, array search )

array_key_exists() 在给定的 key 存在于数组中时返回 TRUEkey 可以是任何能作为数组索引的值。array_key_exists() 也可用于对象。

例子 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";
}
?>

注: 在 PHP 4.0.6 中本函数名为 key_exists()

例子 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);
?>

参见 isset()array_keys()in_array()


add a note add a note User Contributed Notes
josh at nitrotech dot org
29-May-2006 09:24
Here is a simple method for searching nested arrays.

<?php

function in_array_multi_key($needle, $haystack)
{
  
// mutidimentional search for in_array function
   // only matches the key, values don't count.
  
if ( array_key_exists($needle, $haystack) )
   {
       return
TRUE;
   }

   foreach (
$haystack as $key => $value )
   {
       if (
is_array($value) )
       {
          
$work = in_array_multi_key($needle, $value);
           if (
$work )
           {
               return
TRUE;
           }
       }
   }
   return
FALSE;
}

?>

(Code from www.nitrotech.org)
09-May-2006 11:44
property_exists() does the same thing for object properties.