array_key_exists
array_key_exists($key, $array)
Returns true if the array $array contains the key $key, otherwise false. Unlike isset() it also returns true when the value stored under the key is null.
Parameters
- $key – the key to look for (a string or an integer).
- $array – the array to search.
Examples
$user = array("name" => "Garth", "phone" => null);
var_dump(array_key_exists("name", $user)); // bool(true)
var_dump(array_key_exists("email", $user)); // bool(false)
// the difference from isset() – a null value
var_dump(array_key_exists("phone", $user)); // bool(true)
var_dump(isset($user["phone"])); // bool(false)
// the numeric string "1" and the number 1 are the same key
var_dump(array_key_exists("1", array(1 => "a"))); // bool(true)
// safely reading a URL parameter
$page = array_key_exists("page", $_GET) ? (int)$_GET["page"] : 1;
// shorter with the ?? operator (since PHP 7, works like isset)
$page = (int)($_GET["page"] ?? 1);
Things to watch out for
- The function looks for a key, not a value. in_array() looks for a value.
- isset() is faster and enough for most checks, it just treats a null value as missing. Use array_key_exists when you need to tell “the key is missing” from “the key is there but holds null”.
- It searches only the first level of the array. In a nested array check each level separately, or use isset($array["a"]["b"]).
- Using it on an object is deprecated since PHP 7.4 and no longer works in PHP 8. For object properties use property_exists() or isset().
Related functions:
in_array()
array_merge()
json_decode()