PHP 8 reference · Array Functions
PHP array_key_exists() Function
Check whether an array has a given key, even if its value is null. isset() returns false for null values.
PHP 8 Since 4.0
Syntax
array_key_exists(string|int|float|bool|resource|null $key, array $array): bool
Parameters
| Parameter | Description |
|---|---|
key |
The key to look for. |
array |
The input array. |
Return value
true if the key exists.
Examples
<?php
$settings = ["theme" => "dark", "beta" => null];
var_dump(array_key_exists("beta", $settings));
var_dump(isset($settings["beta"]));
Output
bool(true) bool(false)
<?php
$row = ["id" => 7];
echo array_key_exists("email", $row) ? $row["email"] : "no email", "\n";
echo $row["email"] ?? "no email", "\n"; // shorter when null means missing
Output
no email no email
key_exists() is an alias. For speed and brevity, isset($a[$k]) is fine when a null value can be treated as
missing.
Version history
In other languages
dict.get()· PythonObject.hasOwn()· JavaScript
Related
in_array()· Check whether a value exists in an array. Pass true as the third argument for a strict (===) comparison.array_keys()· Return all the keys of an array, or only the keys whose value matches a search value.array_search()· Search an array for a value and return the first matching key, or false if it isn't there.- PHP Arrays · tutorial
- PHP Array Functions · tutorial