Here's a function to return a reference to the first array element that has a given key. The code works for multidimensional arrays:
<?php
function &array_find_element_by_key($key, &$form) {
if (array_key_exists($key, $form)) {
$ret =& $form[$key];
return $ret;
}
foreach ($form as $k => $v) {
if (is_array($v)) {
$ret =& array_find_element_by_key($key, $form[$k]);
if ($ret) {
return $ret;
}
}
}
return FALSE;
}
?>
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);
?>
参见 isset(),array_keys() 和 in_array()。
array_key_exists
Karim Ratib
19-Aug-2008 08:09
19-Aug-2008 08:09
jacobsingh at gmail dot com
17-Jun-2008 06:54
17-Jun-2008 06:54
I saw some examples above for array_keys_exist() or functions to see if multiple keys exist in a given array and return false if any of them don't.
Here is a simpler way to do this:
<?php
function array_keys_exist($keys,$array) {
if (count (array_intersect($keys,array_keys($array))) == count($keys)) {
return true;
}
}
$array = array ('filename' => 'myfile', 'filesize' => 1234, 'filepath' => '/tmp/myfile');
$keys = array('filename','filesize','filepath');
echo array_keys_exist($keys,$array);
//returns true
$keys[] = "somethingelse";
echo array_keys_exist($keys,$array);
//Returns false
?>
mankyd at gmail dot com
29-May-2008 01:29
29-May-2008 01:29
You'll notice several notes on this page stating that isset() is significantly faster than array_key_exists(). This may be true except for one small hitch. isset() will return false for arrays keys that have there value set to NULL, which is therefore not entirely accurate.
Example:
<?php
$foo = array();
$foo['bar'] = NULL;
var_dump(isset($foo['bar']));
var_dump(array_key_exists('bar', $foo));
?>
will output:
bool(false)
bool(true)
Be aware of this!
bplessingerMONKEYleapfroginteractive.com
01-May-2008 12:22
01-May-2008 12:22
I noticed that the function for recursion broke the ability to use this on objects, so I added another check to also allow it to work for objects.
<?php
function array_key_exists_r($needle, $haystack)
{
$result = array_key_exists($needle, $haystack);
if ($result)
return $result;
foreach ($haystack as $v)
{
if (is_array($v) || is_object($v))
$result = array_key_exists_r($needle, $v);
if ($result)
return $result;
}
return $result;
}
?>
tmont
30-Apr-2008 05:54
30-Apr-2008 05:54
The argument of array_key_exists() vs. isset() came up in the workplace today, so I conducted a little benchmark to see which is faster:
<?php
// one-dimensional arrays
$array = array_fill(0,50000,'tommy is the best!');
$arraykeyexists_result = array();
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
if (array_key_exists($i,$array)) {
$arraykeyexists_result[] = 1;
}
else {
$arraykeyexists_result[] = 0;
}
}
$arrtime = round(microtime(true)-$start,3);
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
if (isset($array[$i])) {
$arraykeyexists_result[] = 1;
}
else {
$arraykeyexists_result[] = 0;
}
}
$istime = round(microtime(true)-$start,3);
$totaltime = $arrtime+$istime;
$arrpercentage = round(100*$arrtime/$totaltime,3);
$ispercentage = round(100*$istime/$totaltime,3);
echo "array_key_exists(): $arrtime [$arrpercentage%] seconds\n";
echo "isset(): $istime [$ispercentage%] seconds\n";
?>
On Windows, the output is similar to
array_key_exists(): 0.504 [82.895%] seconds
isset(): 0.104 [17.105%] seconds
On Mac or Linux, isset() is faster but only by a factor of approximately 1.5.
Benjamin*removethis*BeckATgmx.de
09-Mar-2008 03:24
09-Mar-2008 03:24
Hi, i needed a recursive check is a key exists .. so here it is. I Hope it saves you time (-:
<?php
function array_key_exists_r($needle, $haystack)
{
$result = array_key_exists($needle, $haystack);
if ($result) return $result;
foreach ($haystack as $v) {
if (is_array($v)) {
$result = array_key_exists_r($needle, $v);
}
if ($result) return $result;
}
return $result;
}
$test = array(
"L0" => array(
"Über uns" => array(
"name" => "Über uns",
"MenuLast" => 0,
"subMenu" => 8,
"href" => "/admin/pages/admin_page_edit.php?nav_gid=1.1",
"navid" => 1.1,
"posid" => 1,
"klickPath" => 0,
),
"Was wir tun" => array(
"name" => "Über uns",
"MenuLast" => 0,
"subMenu" => 8,
"href" => "/admin/pages/admin_page_edit.php?nav_gid=1.1",
"navid" => 1.1,
"posid" => 1,
"klickPath" => 0,
),
),
);
dumpvar(array_key_exists_r('navid', $test), 'array_key_exists_r(\'navid\', $test)');
?>
Output:
var array_key_exists_r('navid', $test)(boolean): 'true'
packard_bell_nec at hotmail dot com
01-Feb-2008 01:46
01-Feb-2008 01:46
You can check whether a variable is defined by using array_key_exists()!
First, you may ask that no reserved array (would be called $LOCALS) is predefined in function scope (contrast to reserved array $GLOBALS in global scope. To solve it, you can use compact().
Then, you may ask that why property_exists() cannot be used. This is because no reserved function is predefined to create OBJECT containing variables and their values, and no reserved function is predefined to import variables into the current symbol table from an OBJECT. In addition, property_exists() breaks the naming convention of reserved function.
Finally, I show how to check whether a variable is defined by using array_key_exists():
<?php
function too(){
$roo = array_key_exists('foo', compact('foo'));
echo ($roo?'1':'0').'<br/>';
$foo = null;
$roo = array_key_exists('foo', compact('foo'));
echo ($roo?'1':'0').'<br/>';
}
too();
?>
The output will be:
0<br/>
1<br/>
mudsrcool at yahoo dot com
29-Dec-2007 08:19
29-Dec-2007 08:19
If you use func_get_args, you can make a slightly prettier implementation of diogoshaw's function:
<?php
function array_keys_exist() {
$keys = func_get_args();
$haystack = array_shift($keys);
foreach ($keys as $key)
if (!array_key_exists($key, $haystack)) return false;
return true;
}
//Pans out as:
if (array_keys_exist($_GET, 'login', 'user', 'passwd') {
//login;
} else {
//don't login;
}
?>
Erel Segal
13-Nov-2007 04:18
13-Nov-2007 04:18
array_diff can be very slow when the arrays are big. If all you need is to check which elements in array1 are not KEYS in array2, DON'T use:
<?php
array_diff($array1,array_keys($array2))
?>
A much quicker option is:
<?php
foreach ($array1 as $key=>$value) {
if (isset($array2[$key]))
unset($array1[$key]);
}
?>
On my computer, when $array1 has a single element and $array2 has 2600 elements, option 1 takes 50 milli-seconds, and option 2 takes 50 micro-seconds (1000 times less!).
wolf550e at gmail dot com
28-Sep-2007 03:51
28-Sep-2007 03:51
array_key_exists(), at least in 5.2.4, passes the array by value. I conclude this from seeing performance worsen as the array to search got bigger. isset() doesn't have this problem.
diogoshaw at gmail dot com
16-Sep-2007 02:58
16-Sep-2007 02:58
this function very good to use if you need to verify many variables:
<?php
function array_key_exists_r($keys, $search_r) {
$keys_r = split('\|',$keys);
foreach($keys_r as $key)
if(!array_key_exists($key,$search_r))
return false;
return true;
}
?>
e.g.
<?php
if(array_key_exists_r('login|user|passwd',$_GET)) {
// login
} else {
// other
}
?>
works for me, enjoy.
dg shaw.
j_hattersleydykes {at} yahoo uk
27-Aug-2007 08:39
27-Aug-2007 08:39
hey - I thought this function maybe useful to someone somewhere..
It works on an array of the keys you want to check exist. you could pass in the names of form fields and the POST array - suppose it could be useful in aiding form validation.
function array_keys_exist(array $keys, array $toCheck, $whichKey = false)
{
foreach ($keys as $array_key)
{
if (! array_key_exists($array_key, $toCheck))
{
// return first key thats not found.
if ($whichKey)
{
return $array_key;
}
else
{
return false;
}
}
}
// all keys exist
return true;
}
hope someone finds it useful :)
sj-b at hotmail dot de
01-Aug-2007 12:14
01-Aug-2007 12:14
i dont like how empty() works.
an integer with value 0 or a boolean wth
value false (same like zero) counts as
empty too.
[code]function r_empty (&$check)
{
if (!isset($check)) return true;
if ($check == NULL) return true;
return false;
}[/code]
that is a good replacement for
both functions for me.
Lucknut dot xbl at googlemail dot com
19-Jul-2007 01:44
19-Jul-2007 01:44
I found this function very good to use if your want your urls like index.php?login or index.php?register
e.g.
<?php
if( array_key_exists( 'home',$_GET ) ) {
echo "Home - its where the heart is.";
} else if( array_key_exists( 'login',$_GET ) ) {
echo "Login code here!";
} else if( array_key_exists( 'register',$_GET ) ) {
echo "Register code here!";
} else {
echo "Home - its where the heart is.";
}
?>
david at madole dot net
06-Jul-2007 11:11
06-Jul-2007 11:11
Regarding performance differences between isset() and array_key_exists(), the differences may be there, but the function are not always interchangable.
Note that when $a[1] = null then isset($a[1]) == false but array_key_exists(1, $a) == true
eidberger at jakota dot de
12-Jun-2007 04:14
12-Jun-2007 04:14
Just wondered why array_key_exists() makes me a cpu-load of 85% while isset() only needs 35%.
Not a big thing for one time execution, but in my case it have to check 1-dimensional array with ~ 15.000 entries 100 times a second. My code checks a big array for existing entrys and updates them, if needed.
Hopes it helps somebody. Notice that on many other functions, which makes coding more comfortable at the cost of speed.
alishahnovin at hotmail dot com
29-May-2007 01:47
29-May-2007 01:47
Seems the array_key_exists can't find a key in a multidimensional array...
Here's my fix...
<?php
function multi_array_key_exists($needle, $haystack) {
foreach ($haystack as $key=>$value) {
if ($needle==$key) {
return true;
}
if (is_array($value)) {
multi_array_key_exists($needle, $value);
}
}
return false;
}
?>
php at ianco dot co dot uk
10-Apr-2007 04:58
10-Apr-2007 04:58
array_key_exists is case sensitive (at least in PHP 4.3.9). To make a case-insensitive comparison you could use strtolower on both sides.
inker2576 at yahoo dot com
07-Mar-2007 12:01
07-Mar-2007 12:01
Further research on this has turned up that the performance problems are a known, confirmed bug in PHP 5.1.x, and have been fixed in PHP builds after September 2006. You can find the bug report here: http://bugs.php.net/bug.php?id=38812
However, just because it's a fixed bug doesn't really change the conclusion. If you're writing a script and there's any chance it could be used on a PHP 5.1.x server, you should still avoid this function and use isset() or some other kind of test if you want it to run efficiently.
serkan yersen
07-Feb-2007 08:01
07-Feb-2007 08:01
marzetti.marco,
I fixed your function it's is more optimized and working better now.
function regex_array_keys($arr, $pattern){
$results[] = false;
if(!is_array($arr))
return false;
foreach($arr as $key => $val){
if(!is_array($key))
if(preg_match($pattern,$key))
array_push($results,$key);
}
return $results;
}
Matt
02-Dec-2006 05:50
02-Dec-2006 05:50
mikael dot knutsson at gmail dot com:
I don't think it does, at least in PHP5?
For example, this outputs bool(false):
$ar = array ( 'outter' => array ( 'inner' => 1 ) );
var_dump(array_key_exists('inner', $ar));
So it doesn't actually check the inner array for the key 'inner'.
mikael dot knutsson at gmail dot com
25-Nov-2006 08:05
25-Nov-2006 08:05
When dealing with multi-dimensional arrays, this function checks through all keys in the array, including the "child arrays" unlike the array_keys( array, $search ) function which would only check and return from the first level of keys.
Took me a couple of minutes to figure out what was wrong and I hope it helps some people when looking for the right function.
Mike Toppa
04-Aug-2006 01:43
04-Aug-2006 01:43
At least in PHP 4.4.0, array_key_exists is inconsistently sensitive to different data types. For example, if your first argument is a double and the keys in your array are integers, array_key_exists will always return false. If you then cast the first argument to an integer, or even to a string, then you can successfully match. I haven't tested all the possibilities, to see when it'll tolerate different data types and when it won't, so the easiest and safest solution is to cast your first argument to match the data type of the keys.
