PHP
Check if an Array Key Exists (isset vs array_key_exists)
Understand the difference between isset() and array_key_exists() for checking if a key exists in a PHP array, and when to use each for robust code.
<?php
$data = [
'name' => 'John Doe',
'age' => 30,
'city' => null,
'status' => 'active'
];
// Checking for 'name' key using isset()
if (isset($data['name'])) {
echo "'name' is set and not null.
";
}
// Checking for 'city' key using isset()
if (isset($data['city'])) {
echo "'city' is set and not null (this won't print).
";
} else {
echo "'city' is not set or is null according to isset().
";
}
// Checking for 'city' key using array_key_exists()
if (array_key_exists('city', $data)) {
echo "'city' key exists, regardless of its value (this will print).
";
}
// Checking for a non-existent key
if (!array_key_exists('country', $data)) {
echo "'country' key does not exist.
";
}
?>
How it works: This snippet demonstrates two ways to check for the existence of a key in a PHP array: isset() and array_key_exists(). The key difference is that isset() returns false if the key's value is null, while array_key_exists() returns true as long as the key is present, regardless of its associated value. array_key_exists() is preferred when you need to distinguish between a key not existing and a key existing with a null value, ensuring more precise condition checks.