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?
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With