If you’re working with arrays in PHP, one common task is checking whether a specific key exists. PHP provides a built-in function for this called array_key_exists().
In this guide, you’ll learn:
- What
array_key_exists()does - How it differs from
isset() - When to use each function
- Practical examples to clarify usage
🔍 What Is array_key_exists() in PHP?
The array_key_exists() function checks whether a specific key exists in an array. Unlike isset(), it returns true even if the corresponding value is null or an empty string.
Syntax:
array_key_exists(mixed $key, array $array): bool
$key: The key you want to check$array: The array you are checking in- Returns:
trueif the key exists,falseotherwise
✅ Example of array_key_exists() Usage:
$products = array(
'first' => null,
'second' => 'Towels',
'third' => 'Soaps'
);
if (array_key_exists('first', $products)) {
echo 'The "first" key is defined in the products array.';
}
Even though the value of 'first' is null, the array_key_exists() function returns true because the key itself exists.
⚠️ Difference Between array_key_exists() and isset()
While both functions check for the presence of a key, there’s an important distinction:
array_key_exists()→ Returns true even if the value isnullisset()→ Returns false if the value isnullor not set
Example Comparison:
isset($products['first']); // Returns false
array_key_exists('first', $products); // Returns true
Use isset() when you care both about the key’s existence and that its value is not null. Use array_key_exists() when you only care about the key’s presence.
🧠 When to Use array_key_exists()
- When validating keys in user-submitted data
- When checking for configuration options in associative arrays
- When building APIs or forms that allow nullable values
📌 Final Thoughts
The array_key_exists() function is an essential tool for PHP developers when handling associative arrays. It ensures that your code can detect whether an expected key is present, regardless of its value.
For more strict checking (e.g. ignoring keys with null values), combine it with isset() or additional validation.
💬 Got Questions?
Feel free to ask your questions or share your thoughts in the comments section below! Hire a PHP Developer.
