Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's quicker and better to determine if an array key exists in PHP?

Consider these 2 examples...

$key = 'jim';  // example 1 if (isset($array[$key])) {     // ... }  // example 2     if (array_key_exists($key, $array)) {     // ... } 

I'm interested in knowing if either of these are better. I've always used the first, but have seen a lot of people use the second example on this site.

So, which is better? Faster? Clearer intent?

like image 593
alex Avatar asked Mar 31 '09 06:03

alex


People also ask

How do you check if a key exists in an array PHP?

PHP array_key_exists() Function The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist.

Which function is used to check if a key is set in the array?

The array_key_exists() function is used to check whether a specified key is present in an array or not. The function returns TRUE if the given key is set in the array. The key can be any value possible for an array index.

What is the main benefit of the array keyword in PHP?

Advantage of PHP ArrayLess Code: We don't need to define multiple variables. Easy to traverse: By the help of single loop, we can traverse all the elements of an array. Sorting: We can sort the elements of array.

What's the difference between isset () and array_key_exists ()?

Difference between isset() and array_key_exists() Function: The main difference between isset() and array_key_exists() function is that the array_key_exists() function will definitely tells if a key exists in an array, whereas isset() will only return true if the key/variable exists and is not null.


1 Answers

isset() is faster, but it's not the same as array_key_exists().

array_key_exists() purely checks if the key exists, even if the value is NULL.

Whereas isset() will return false if the key exist and value is NULL.

like image 96
Richard Levasseur Avatar answered Oct 19 '22 11:10

Richard Levasseur