array_key_exists
Checks whether an array has a key.
Syntax
array_key_exists(string|int $key, array $array): boolParameters
| Parameter | Type | Description |
|---|---|---|
| $key | string|int | The key to check. |
| $array | array | The array. |
Return value
bool`true` if the key exists.
Examples
A present key and a missing one:
<?php
$user = ['name' => 'Anna', 'email' => null];
var_dump(array_key_exists('name', $user));
var_dump(array_key_exists('phone', $user));Output:
bool(true)
bool(false)The difference from isset(): a key holding null exists:
<?php
$user = ['email' => null];
var_dump(array_key_exists('email', $user));
var_dump(isset($user['email']));Output:
bool(true)
bool(false)Notes
isset() or the ?? operator is usually enough. array_key_exists() is needed when null is a valid value.
See also
- in_array — Checks whether a value exists in an array.
- isset — Checks that a variable exists and is not null.
- array_keys — Returns all the keys of an array.
Related recipes
In the tutorial
- Arrays — Lists and associative arrays in PHP — creating, changing, iterating and useful functions.