PHP array_key_exists: Check if Key Exists in Array

This article explains how to use the array_key_exists() function in PHP to determine whether a specific key or index is present within an associative array. You will learn the correct syntax, see practical code examples, and understand the crucial differences between array_key_exists() and the isset() function when handling null values.

Syntax of array_key_exists()

The array_key_exists() function is a built-in PHP function that returns a boolean value (true or false). It takes two arguments:

array_key_exists(mixed $key, array $array): bool

Basic Example

Here is a straightforward example of how to check if a key exists in an associative array of user data:

<?php
$user = [
    'username' => 'johndoe',
    'email' => 'john@example.com',
    'age' => 30
];

if (array_key_exists('email', $user)) {
    echo "The key 'email' exists in the array.";
} else {
    echo "The key 'email' does not exist in the array.";
}
?>

Difference Between array_key_exists() and isset()

While both array_key_exists() and isset() can check for key existence, they behave differently if the key exists but its value is set to null.

Code Comparison

<?php
$data = [
    'status' => null
];

// Returns true because the key 'status' physically exists
var_dump(array_key_exists('status', $data)); // Output: bool(true)

// Returns false because the value of 'status' is null
var_dump(isset($data['status'])); // Output: bool(false)
?>

Use array_key_exists() when you need to confirm the presence of a key regardless of what value it holds. Use isset() when you want to ensure the key exists and does not contain a null value.