开发者

How to check if an array has an element at the specified index?

I know there is array_key_exists() but after reading the documentation I'm not really sure if it fits for this case:

I have an $array and an $index. Now I 开发者_高级运维want to access the $array, but don't know if it has an index matching $index. I'm not talking about an associative array, but an plain boring normal numerically indexed array.

Is there an safe way to figure out if I would really access an $array element with the given $index (which is an integer!)?

PHP may not care if I access an array with an index out of bounds and maybe just returns NULL or so, but I don't want to even attempt to code dirty, so I want to check if the array has the key, or not ;-)


You can use either the language construct isset, or the function array_key_exists : numeric or string key doesn't matter : it's still an associative array, for PHP.

isset should be a bit faster (as it's not a function), but will return false if the element exists and has the value NULL.


For example, considering this array :

$a = array(
    123 => 'glop', 
    456 => null, 
);

And those three tests, relying on isset :

var_dump(isset($a[123]));
var_dump(isset($a[456]));
var_dump(isset($a[789]));

You'll get this kind of output :

boolean true
boolean false
boolean false

Because :

  • in the first case, the element exists, and is not null
  • in the second, the element exists, but is null
  • and, in the third, the element doesn't exist


On the other hand, using array_key_exists like in this portion of code :

var_dump(array_key_exists(123, $a));
var_dump(array_key_exists(456, $a));
var_dump(array_key_exists(789, $a));

You'll get this output :

boolean true
boolean true
boolean false

Because :

  • in the two first cases, the element exists -- even if it's null in the second case
  • and, in the third, it doesn't exist.


You can easily use isset():

if (isset($array[$index])) {
   // array index $index exists
}

And as you have suggested, PHP is not very kind if you try to access a non-existent index, so it is crucial that you check that you are within bounds when dealing with accessing specific array indexes.

If you decide to use array_key_exists(), please note that there is a subtle difference:

isset() does not return TRUE for array keys that correspond to a NULL value, while array_key_exists() does.


That's exactly what the array_key_exists is for. It works on both numerical and string indexes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜