PHP
Safely Check if Array Key Exists
Master the essential difference between array_key_exists and isset() for securely checking if a key is present in a PHP array, handling null values correctly.
$config = ['username' => 'admin', 'password' => null, 'email' => ''];
// Check if 'username' key exists
if (array_key_exists('username', $config)) {
echo "Username key exists.
";
}
// Check if 'password' key exists (value is null)
if (array_key_exists('password', $config)) {
echo "Password key exists, even if its value is null.
";
}
// Using isset() for comparison
if (isset($config['password'])) {
echo "Password is set (this won't print as value is null).
";
} else {
echo "Password is not set (from isset()).
";
}
// Check for a non-existent key
if (!array_key_exists('api_key', $config)) {
echo "API key does not exist.
";
}
How it works: The `array_key_exists()` function checks if a specified key or index exists in an array. Crucially, it returns `true` even if the value associated with the key is `null`. This distinguishes it from `isset()`, which returns `false` for `null` values, making `array_key_exists()` ideal for situations where a key's mere presence, regardless of its value, is more important than its non-null status.