Asked : Nov 17
Viewed : 62 times
I have two types of array 1. Indexed arrays and 2. Associative Array. I need help to check key exists in an array or not.
1. Indexed arrays
$index_array = ['apple', 'pear', 'banana'];
2. Associative Array
$associative_array= array('first' => null, 'second' => 4);
What's quicker and better to determine if an array key exists in PHP?
I am interested in knowing if either of these is better. I have 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?
Nov 17
If you are interested in some tests I've done recently:
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 exists and value is NULL
.
1. Indexed arrays
// Here's our fruity array
$index_array = ['apple', 'pear', 'banana'];
// Use it in an `if` statement
if (array_key_exists("banana", $index_array)) {
// Do stuff because `banana` exists
}
// Store it for later use
$exists = array_key_exists("peach", $index_array);
// Return it directly
return array_key_exists("pineapple", $index_array);
2: Associative Array
$associative_array= array('first' => null, 'second' => 4);
// returns false
isset($associative_array['first']);
// returns true
array_key_exists('first', $associative_array);
answered Nov 26