PHP has two inbuilt functions array_key_exists()
& key_exists()
, and with the help of these functions you can check whether a key exists in an array or not.
The key_exists()
function is alias of array_key_exists()
. Both do the same thing.
PHP array_key_exists() function
array_key_exists(key, array)
- This function takes two parameters, the key you want to find and the array where you want to search.
- It will return true if the given key is present in the array, else it will return false.
<?php
$marks = [
"John" => 75,
"Mark" => 62,
"Smith" => 58,
"Jane" => 87
];
if(array_key_exists("Smith", $marks)){
echo "The key exists in the array";
}
else{
echo "The key is not in the array";
}
The key exists in the array