To check if a key exists in a PHP array, you can use the array_key_exists
function. This function returns a boolean value indicating whether the given key exists in the array.
Here’s an example:
$array = ['a' => 1, 'b' => 2, 'c' => 3];
if (array_key_exists('a', $array)) {
// The key 'a' exists in the array
}
if (array_key_exists('d', $array)) {
// The key 'd' does not exist in the array
}
You can also use the isset
function to check if a key exists in an array, but it will only return true
if the key is set and is not null
.
$array = ['a' => 1, 'b' => 2, 'c' => 3];
if (isset($array['a'])) {
// The key 'a' exists in the array and is not null
}
if (isset($array['d'])) {
// This code will not be executed because the key 'd' does not exist in the array
}
$array['d'] = null;
if (isset($array['d'])) {
// The key 'd' exists in the array but is null
}