PHP Check if Array Key Exists: Complete Guide
In PHP, the function array_key_exists() can be used to determine if a key exists in an array. An example is shown below:
$array = array("name" => "John", "age" => 30, "city" => "New York");
if (array_key_exists("name", $array)) {
echo "Key 'name' exists in the array";
} else {
echo "Key 'name' does not exist in the array";
}
Additionally, you can use the isset() function to check if a key exists in an array. An example is shown below:
$array = array("name" => "John", "age" => 30, "city" => "New York");
if (isset($array["name"])) {
echo "Key 'name' exists in the array";
} else {
echo "Key 'name' does not exist in the array";
}
The difference between array_key_exists() and isset() functions is that isset() returns true only when the key exists and its corresponding value is not null, whereas array_key_exists() only checks if the key exists.