array_key_exists()
This function is used to check if a key exists or not in an array. It takes two parameters, the first one being the key you are looking for and the second one the actual array. It returns true or false.
Formula: array_key_exists(‘KeyName’, $array)
Returns: Boolean (TRUE or FALSE)
Key exists in array
Example:
$array1 = ['Manchester' => 1, 'London' => 2, 'New York' => 3];
if(array_key_exists('Manchester', $array1)) { // returns true
echo 'Found key: ' . $array1['Manchester'];
}
Output:
Found key: 1
If Manchester would not exist in this array and we would not check that the key exists within the array before trying to get the value for Manchester, the code would fail showing this exception: Undefined index: Manchester.
Example:
$array1 = ['London' => 2, 'New York' => 3];
$array1['Manchester'];
Output:
Undefined index: Manchester
NOTE: this function doesn’t work on arrays where the values are not in the format of key => value. Therefore, if you are trying to use array_key_exists() on the following array, it will not work.
Example of an array without key => value:
$array = ['Manchester', 'London', 'New York'];
echo array_key_exists('Manchester', $array); // returns false
Read more about in_array() if you are looking for a solution for the above example.
Check key exists in array of arrays (two-dimensional)
Let’s assume you want to parse an array of arrays and want to check if any of the object arrays contains a key. This can be done using a foreach() loop in PHP.
Example:
$array = [
[
'object1' => 1,
'object2' => 2,
],
[
'test' => 'lol'
]
];
foreach ($array as $items) {
if(array_key_exists('test', $items)) { // returns true
echo 'Found key: ' . $items['test];
}
}
Output:
Found key: lol
Check key exists in array of arrays of arrays (three-dimensional)
Now, let’s assume you want to parse an array of arrays of arrays. This can be accomplished using two forloops().
Example:
$array3 = [
[
[
'object1' => 1,
'object2' => 2,
],
[
'object3' => 3,
'object4' => 4,
]
],
[
[
'object5' => 5,
'object6' => 6,
],
[
'object7' => 7,
'object8' => 8,
]
]
];
foreach ($array3 as $items) {
foreach ($items as $item) {
if (array_key_exists('object4', $item)) { // returns true
echo 'Found key: ' . $item['object4'];
}
}
}
Output:
Found key: 4
In conclusion, array_key_exists() is very helpful in many ways, improving the code readability and also performance. However, as it is always the case, it all depends on the array structure and the objective your code tried to accomplish.