I tested the rapidity of isset vs array_key_exists. I always thougt that array_key_exists would be the winner ...
Here is my script :
┌─(yoda@ev5)(14:25:29) └─(~/var/www/test)-> cat isset_array-key-exists.php #!/usr/bin/php <?php define('N', "\n"); error_reporting(E_ALL | E_NOTICE); $nbLoop = 10000; $testArray = array('foo' => 'bar', 'bar' => 'quux'); $time = array(); $desc = array( 0 => 'array_key_exists on existant key', 1 => 'array_key_exists on non existant key', 2 => 'isset on existant key', 3 => 'isset on non existant key', ); /** * begin with array_key_exists, existant key */ $time[0]['start'] = microtime(true); for($i = 0; $i < $nbLoop; $i++) { array_key_exists('foo', $testArray); } $time[0]['stop'] = microtime(true); /** * begin with array_key_exists, non existant key */ $time[1]['start'] = microtime(true); for($i = 0; $i < $nbLoop; $i++) { array_key_exists('foz', $testArray); } $time[1]['stop'] = microtime(true); /** * begin with isset, existant key */ $time[2]['start'] = microtime(true); for($i = 0; $i < $nbLoop; $i++) { isset($testArray['foo']); } $time[2]['stop'] = microtime(true); /** * begin with isset, non existant key */ $time[3]['start'] = microtime(true); for($i = 0; $i < $nbLoop; $i++) { isset($testArray['foz']); } $time[3]['stop'] = microtime(true); $differences = array(); echo 'results: '.N; foreach($time as $k => $t) { echo 'test '.$k.' "'.sprintf('%40s', $desc[$k]).'" : '.($difference[$k] = $t['stop'] - $t['start']).N; }
And here is the results :
┌─(yoda@ev5)(14:25:32) └─(~/var/www/test)-> php isset_array-key-exists.php results: test 0 " array_key_exists on existant key" : 0.00795984268188 test 1 " array_key_exists on non existant key" : 0.00665903091431 test 2 " isset on existant key" : 0.00737690925598 test 3 " isset on non existant key" : 0.00131511688232
And the winner is : isset !
1 De neolitec -
Testé et approuvé ! (PHP 5.2.10)
A un détail près !
isset et array_key_exists ne renvoient pas toujours la même chose dans un cas précis :
$array['foo'] = null;
isset($array['foo']); // false
array_key_exists('foo', $array); // true
Logique, isset teste la valeur qu'on lui passe en paramètre, alors que array_key_exists fait exactement ce pour quoi elle a été faite : elle regarde si la clé existe.
Mais... si on est certain de ne pas avoir de valeurs nulles...
=D