(PHP 4 >= 4.0.7, PHP 5)
array_key_exists — 检查给定的键名或索引是否存在于数组中
array_key_exists() 在给定的 key
存在于数组中时返回 TRUE
。key
可以是任何能作为数组索引的值。 array_key_exists()
也可用于对象。
key
要检查的键。
search
一个数组,包含待检查的键。
成功时返回 TRUE
, 或者在失败时返回 FALSE
。
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:
为了向下兼容,可以使用下列已废弃的别名: key_exists()
Note:
For backward compatibility reasons, array_key_exists() will also return
TRUE
ifkey
is a property defined within an object given assearch
. This behaviour should not be relied upon, and care should be taken to ensure thatsearch
is an array.To check whether a property exists in an object, use property_exists().
Sandro Alves Peres (2013-06-19 11:30:39)
<?php
/*
It also works on objects
***************************************
*/
class PHP
{
private $compiler;
protected $architecture;
public $version;
public $system = "Linux";
}
$php = new PHP();
$a = array_key_exists('compiler', $php); # false
$b = array_key_exists('architecture', $php); # false
$c = array_key_exists('version', $php); # true
$d = array_key_exists('system', $php); # true
var_dump( $a, $b, $c, $d );
?>
Anonymous (2013-06-19 11:30:31)
<?php
/*
It also works on objects
***************************************
*/
class PHP
{
private $compiler;
protected $architecture;
public $version;
public $system = "Linux";
}
$php = new PHP();
$a = array_key_exists('compiler', $php); # false
$b = array_key_exists('architecture', $php); # false
$c = array_key_exists('version', $php); # true
$d = array_key_exists('system', $php); # true
var_dump( $a, $b, $c, $d );
?>
Karl Kloppenborg karl at influ dot io (2013-05-07 01:59:55)
Just a follow up to tom at edgedesigns dot org's multidimensional key_exists - despite him stating that it will always return the correct result, it doesn't because the if statement for $needle equals $key wasn't implicit, he was using the 'equal' comparison operator instead of the 'identical' operator.
The correct [updated] code is:
function multi_array_key_exists( $needle, $haystack ) {
foreach ( $haystack as $key => $value ) :
if ( $needle === $key ) {
return true;
}
if ( is_array( $value ) ) :
if ( multi_array_key_exists( $needle, $value ) === true )
return true;
else
continue;
endif;
endforeach;
return false;
}
--Karl.
imaginary at friend dot com (2012-04-09 16:37:35)
An even simpler case-insensitive alternative to array_key_exists():
<?php
array_key_exists(strtolower($key), array_change_key_case($search));
Nik Tang (2012-03-05 01:22:45)
If you want to take the performance advantage of isset() while keeping the NULL element correctly detected, use this:
if (isset(..) || array_key_exists(...))
{
...
}
Benchmark (100000 runs):
array_key_exists() : 205 ms
is_set() : 35ms
isset() || array_key_exists() : 48ms
Note:
The code for this check is very fast, so you shouldn't warp the code into a single function like below, because the overhead of calling a function dominates the overall performance.
function array_check(...)
{
return (isset(..) || array_key_exists(...))
}
Rudi (2011-11-10 02:10:45)
I've got a new take on the multi key function I would like to share.
<?php
function array_multi_key_exists(array $arrNeedles, array $arrHaystack, $blnMatchAll=true){
$blnFound = array_key_exists(array_shift($arrNeedles), $arrHaystack);
if($blnFound && (count($arrNeedles) == 0 || !$blnMatchAll))
return true;
if(!$blnFound && count($arrNeedles) == 0 || $blnMatchAll)
return false;
return array_multi_key_exists($arrNeedles, $arrHaystack, $blnMatchAll);
}
?>
Hope you'll find it usefull.
glitch dot mr at gmail dot com (2011-10-01 04:15:07)
As you might know, isset() is actually working like @$variable===NULL. As the result, it doesn't actually catch variables set to NULL. If you want to check if variable is set (even to NULL), you can use array_key_exists on $GLOBALS, like there.
<?php
$me = null;
$se = 1;
unset($se);
// $he is not set
if(array_key_exists('me', $GLOBALS)) echo "\$me exists\n";
if(array_key_exists('se', $GLOBALS)) echo "\$se exists\n";
if(array_key_exists('he', $GLOBALS)) echo "\$he exists\n";
?>
In this case, only $me will be detected as $se was removed when code was running and $he was never set.
Anonymous (2011-06-16 13:07:29)
I just want to note that array_key_exists() can be extremely slow for large (>200 keys) arrays. Use isset($array($key)) instead! My program ran in 3 minutes instead of 2 hours after switching to isset()!
manhon824 at gmail dot com (2011-05-18 09:29:54)
I took hours for me to debug, and I finally recognized that,
You have to reset the $array before using array_key_exists
reset($array);
array_key_exists($needle,$array);
Or you will get no reply.
tech at signhere envy dot de (2011-01-18 02:23:20)
Hey, this function is able to rename a key inside an array.
If the key to be replaced doesn't exist inside the array, or the new key already exists in the array, the function will return FALSE.
Otherwise, the array with the renamed key will be returned.
Hope this will be useful for someone.
<?php
function array_rename_key($array, $key, $newkey){
if( ! array_key_exists($key, $array) || array_key_exists($newkey, $array)) return FALSE;
$uid = uniqid(''); //To clearly identify the Element.
$preserve_value = $array[$key]; //Keep the Value
$array[$key] = $uid; //Overwrite Value with ID
$array = array_flip($array); //Flip the Array keys and values
$array[$uid] = $newkey; //Set Value of the ID with new Key.
$array = array_flip($array); //Everything back in Place.
$array[$newkey] = $preserve_value;
return $array;
}
?>
jens dot hoevenaars at gmail dot com (2010-11-06 15:21:04)
I created this function that uses array key exist to compare a form and a table to see if something has changed.
This can be very helpfull if you need to update a table record from a form but you do not want to display all table fields.
<?php
function($data_from_db, $form_data) {
$data = $data_from_db;
$keys = array_keys($data);
for($i = 0; $i < count($data); $i++) {
if(!array_key_exists($keys[$i], $form_data)) {
$dbobject->$keys[$i] = $data[$keys[$i]];
} else {
$dbobject->$keys[$i] = $form_data[$keys[$i]];
}
}
return $dbobject;
}
?>
you can then use the dbobject to update the table.
moandsimon at btinternet dot com (2010-04-26 01:56:41)
This uses array_key_exists.
You have a multidimensional array of the form:
$rowsoriginal[] = array('field_wrkvolmin_value' => 216, 'field_wrkvolmax_value' => 1000);
$rowsoriginal[] = array('field_wrkvolmin_value' => 27, 'field_wrkvolmax_value' => 216);
Using print_r this will look like:
Array ( [0] => Array ( [field_wrkvolmin_value] => 216 [field_wrkvolmax_value] => 1000 ) [1] => Array ( [field_wrkvolmin_value] => 27 [field_wrkvolmax_value] => 216 ) )
This can be used to create a table by iterating over the rows that looks like this:
field_wrkvolmin_value field_wrkvolmax_value
216 1000
27 216
when $rowsoriginal contain a fixed but unknown amount of values.
If you want to process this in an automatic way without knowing the keys etc, into a multidimensional array of the form:
$rowstemp = array('field_wrkvolmin_value' => array(216, 27), 'field_wrkvolmax_value' => array(1000, 216));
Using print_r this will look like:
Array ( [field_wrkvolmin_value] => Array ( [0] => 216 [1] => 27 ) [field_wrkvolmax_value] => Array ( [0] => 1000 [1] => 216 ) )
This can be used to iterate over the rows of a table to create a table in the form of:
field_wrkvolmin_value 216 27
field_wrkvolmax_value 1000 216
To do this you can use the following looping and conditional structure, using array_key_exists():
<?php
$rowstemp = array();
foreach ($rowsoriginal as $row) {
foreach ($row as $key => $value) {
if (array_key_exists($key, $rowstemp)) {
$rowstemp[$key][] = $value;
}
else {
$valuestemp = array($value);
$rowstemp[$key] = $valuestemp;
}
}
}
?>
gmdebby at gmail dot com (2010-01-14 05:44:49)
A little function which take an array as keys
<?php
//note the s in the function name (keys)
function array_keys_exists($array,$keys) {
foreach($keys as $k) {
if(!isset($array[$k])) {
return false;
}
}
return true;
}
?>
//useful to validate a form for example
<form>
<input type="text" name="field1" /><br />
<input type="text" name="field2" /><br />
<input type="text" name="field3" /><br />
<input type="text" name="field4" /><br />
<input type="text" name="field5" /><br />
</form>
<?php
if(!array_keys_exists($_POST,
array("field1","field2","field3","field4","field5")
)) {
//some fields are missing, dont do anything (maybe hacking)
} else {
//code ...
}
?>
Darkless at seznam dot cz (2009-11-13 09:17:48)
a bit upgraded multi_array_key_exists function
@param needle string to be searched in keys
@param haystack array to be searched in
@return false when it was not found or string structured by name of keys devided by ":"
eg $arrays = array ('first' => array ( 'one'=> 'anything'));
for multi_array_key_exists('one',$arrays) it returns:
"first:one" by explode you can then write sth like $array[$path[0]][$path[1]]...
<?php
function multi_array_key_exists($needle, $haystack) {
foreach ($haystack as $key=>$value) {
if ($needle===$key) {
return $key;
}
if (is_array($value)) {
if(multi_array_key_exists($needle, $value)) {
return $key . ":" . multi_array_key_exists($needle, $value);
}
}
}
return false;
}
?>
PHPEric (2009-08-05 06:51:29)
Very simple case-insensitive array_key_exists:
bool (in_array(strtolower($needle), array_map('strtolower', array_keys($haystack))))
tom at edgedesigns dot org (2009-07-21 05:10:01)
The multi_array_key_exists() function posted by alishahnovin at hotmail dot com [which has since been removed] does not always return the expected result.
This modified version does.
<?php
/**
* multi_array_key_exists function.
*
* @param mixed $needle The key you want to check for
* @param mixed $haystack The array you want to search
* @return bool
*/
function multi_array_key_exists( $needle, $haystack ) {
foreach ( $haystack as $key => $value ) :
if ( $needle == $key )
return true;
if ( is_array( $value ) ) :
if ( multi_array_key_exists( $needle, $value ) == true )
return true;
else
continue;
endif;
endforeach;
return false;
}
?>
webmaster at oehoeboeroe dot nl (2009-05-04 13:09:06)
The way array_key_exists handles null, float, boolean, and 'integer-representing string' keys is inconsistent in itself and, in the case of bool and float, with the way these are converted when used as array offset.
<?php
$array = array(null => 1, false => 2, true => 3, 4.6 => 4, "08" => 5, "8" => 6);
var_export($array);
echo "\nnull is " . (array_key_exists(null, $array) ? '' : 'not ') . "a key.\n";
echo 'false is ' . (array_key_exists(false, $array) ? '' : 'not ') . "a key.\n";
echo 'true is ' . (array_key_exists(true, $array) ? '' : 'not ') . "a key.\n";
echo '4.6 is ' . (array_key_exists(4.6, $array) ? '' : 'not ') . "a key.\n";
echo '"08" is ' . (array_key_exists("08", $array) ? '' : 'not ') . "a key.\n";
echo '"8" is ' . (array_key_exists("8", $array) ? '' : 'not ') . "a key.\n";
?>
Output:
array (
'' => 1,
0 => 2,
1 => 3,
4 => 4,
'08' => 5,
8 => 6,
)
null is a key.
false is not a key.
true is not a key.
4.6 is not a key.
"08" is a key.
"8" is a key.
Well, and you get this warning three times (on the bools and the float, but not on the null):
Warning: array_key_exists() [function.array-key-exists]: The first argument should be either a string or an integer in /var/www/php/test.php on line 6
Gibson SG (2009-02-25 15:55:08)
Below is a more efficient and useful case-insensitive array_key_exists function. More useful in the sense that it returns the matching key.
<?php
/**
* Case insensitive version of array_key_exists.
* Returns the matching key on success, else false.
*
* @param string $key
* @param array $search
* @return string|false
*/
function array_key_exists_nc($key, $search) {
if (array_key_exists($key, $search)) {
return $key;
}
if (!(is_string($key) && is_array($search) && count($search))) {
return false;
}
$key = strtolower($key);
foreach ($search as $k => $v) {
if (strtolower($k) == $key) {
return $k;
}
}
return false;
}
/* Test code: */
$array = array(
'taste' => 'sweet',
'cOlOr' => 'yellow',
'foo',
'bar',
);
$keys = array(
'Color',
'google',
0,
);
foreach ($keys as $key) {
print "\t$key: "; var_dump(array_key_exists_nc($key, $array));
}
/* Output:
Color: string(5) "cOlOr"
google: bool(false)
0: int(0)
*/
?>
csaba at alum dot mit dot edu (2009-01-20 05:13:15)
In some functions cacheing can be extremely useful, and this is especially true in recursive functions, and all the more so in doubly recursive functions. One way to effect cacheing is to have a static array in the function as shown below. This will typically be useful when a function has one or two arguments and is heavily called. Example:
<?php
function nk($n, $k) {
// n choose k, ensuring integer math
if ($k > $n-$k) $k = $n - $k; // (n,k) = (n,n-k)
if ($k<=1) return ($k==1) ? $n : !$k; // (n,1) = n; (n,0)=1; (n,-#) = 0
static $aNK = array(); // caching section
if ($aNK[$n][$k]) return $aNK[$n][$k];// if answer already computed => done
// else compute answer, cache it, and return
return ($aNK[$n][$k] = nk($n-1, $k) + nk($n-1, $k-1)); }
$n = 20;
$k = 9;
$nk = nk($n,$k);
print "nk($n, $k) = $nk";
?>
For functions of two arguments, using a two dimensional array seems to be faster than combining arguments a la "$n $k", and the form of testing shown above is also faster than array_key_exists. However, to avoid the use of array_key_exists, special consideration must be given to empty values (several prior notes cover this) - the example above works because no cached value can be 0.
Csaba Gabor from Vienna
John (2009-01-18 21:27:41)
Here is a little function for case sensitivity to elaborate on what was said by MarkL from ##php (Freenode) and mmanning at mdanderson dot org from this page:
<?php
// Case sensitive version of array_key_exists() using preg_match()
function array_ikey_exists($key,$arr)
{
if(preg_match("/".$key."/i", join(",", array_keys($arr))))
return true;
else
return false;
}
?>
Not that anyone else couldn't have written this, but a concept like this strengthens reusability. :)
Also, I've been running into issues with escaping for Regex, so I decided to give something like this a shot:
<?php
function array_ikey_exists($key,$arr)
{
$e = 0; //$key = addslashes($key);
if(is_array($arr) && $arr !==array())
{
foreach($arr as $k => $v)
{
if(strtolower($k) == strtolower($key))
$e++;
}
if($e>0)
return true;
else
return false;
}
else
return false;
}
?>
You could addslashes() to escape; it's just another approach.
david at lostair dot com (2008-12-07 00:07:40)
It is important to realise that:
isset($array ['index'])
Does not act the same as:
array_key_exists('index', $array)
This is because if an array value is set to NULL
$array['index'] = NULL;
Then isset will return FALSE and array_key_exists will return TRUE.
It is important to realise this!
mmanning at mdanderson dot org (2008-10-21 08:13:50)
Something to keep in mind is that array_key_exists is case sensitive. So two things I'd like to say:
1. Could there be an additional option added on to the array_key_exists command so you can specify the case to be insensitive?
2. Here is how you can do this test in one command:
if( preg_match("/<key>/i", join(",", array_keys(<array>))) ){
<Do something>
}
But it would be a lot nicer to just have an additional option on the array_key_exists. Like so:
array_key_exists(<array>, ["i"] );
Ok - so why did this come up at all? I wrote a routine to convert any whacky UppERcAsE kind of lettering to just be lowercase letters. (ex: FgColorS becomes fgcolors and so forth.) So I never had to guess what the user was putting in to the program. There were two particular items (fgColors and bgColors) which I wanted to test against. If they were not supplied, my program would supply them. The above was the easiest way I could come up with to do this. :-)
Karim Ratib (2008-08-19 05:09:01)
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;
}
?>
jacobsingh at gmail dot com (2008-06-17 03:54:49)
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 (2008-05-28 10:29:48)
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 (2008-04-30 09:22:20)
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 (2008-04-29 14:54:24)
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 (2008-03-08 11:24:19)
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 (2008-01-31 09:46:09)
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 (2007-12-29 04:19:00)
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 (2007-11-13 00:18:41)
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 (2007-09-27 12:51:24)
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 (2007-09-15 11:58:02)
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 (2007-08-26 17:39:40)
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 (2007-07-31 21:14:49)
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 (2007-07-18 10:44:38)
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 (2007-07-05 20:11:15)
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 (2007-06-11 13:14:17)
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.
php at ianco dot co dot uk (2007-04-09 13:58:09)
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 (2007-03-06 20:01:42)
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 (2007-02-07 04:01:43)
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 (2006-12-01 13:50:28)
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 (2006-11-24 16:05:03)
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 (2006-08-03 10:43:56)
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.