Page 1 of 1

Is array_key_exists superfluous?

Posted: Wed Mar 21, 2007 4:52 pm
by ryos
This post is pure curiosity. Is there any reason to use:

Code: Select all

array_key_exists ($key, $array);
...instead of:

Code: Select all

isset ($array[$key]);
...beyond, of course, stylistic preference?

TIA for your opinions.

Posted: Wed Mar 21, 2007 5:29 pm
by Christopher
I believe array_key_exists() will search an entire multi-dimensional array for a key.

Posted: Wed Mar 21, 2007 6:30 pm
by Chris Corbyn
arborint wrote:I believe array_key_exists() will search an entire multi-dimensional array for a key.
I don't see that in the manual and I was not under that impression myself :)

The last comment in the manual reveals that this function is slower than using isset(). I seem to interchange between the two quite a lot which is bad I guess but array_key_exists() could be used in a more contextual sense when you want to make it clear you're looking for an ite in a container, not just the presence of a variable.

Posted: Wed Mar 21, 2007 6:35 pm
by harrisonad
yeah, array_key_exists() may spit 'undefined vars' error.

Posted: Wed Mar 21, 2007 9:50 pm
by feyd
isset() fails when a the value of the element is null. array_key_exists() does not look at the value.

Posted: Wed Mar 21, 2007 11:48 pm
by volka
e.g.

Code: Select all

$arr = array(1=>null);
echo 'isset: ', isset($arr[1]) ? 'yes':'no', "\n";
echo 'exists: ', array_key_exists(1, $arr) ? 'yes':'no', "\n";
isset: no
exists: yes

Posted: Thu Mar 22, 2007 12:27 am
by Luke
off topic, but how come you send multiple string parameters to echo instead of just concatenating? Is there any benefit or is it just preference?

Code: Select all

echo 'this ', 'is ', 'a ', 'string';
instead of:

Code: Select all

echo 'this ' . 'is ' . 'a ' . 'string';

Posted: Thu Mar 22, 2007 12:31 am
by feyd
less processing required.

Posted: Thu Mar 22, 2007 1:31 am
by Kieran Huggins
feyd wrote:less processing required.
8O

You learn something new every day!

Posted: Thu Mar 22, 2007 2:29 am
by Chris Corbyn
Kieran Huggins wrote:
feyd wrote:less processing required.
8O

You learn something new every day!
Logical when you think about it. Do the concatenation way and PHP needs to write new values to memory before adding it to the buffer and flushing. Use commas and PHP just uses the values already in memory.