How to check if a key exists in an array
Short answer
isset() returns true if the key exists and the value is not null:
<?php
$user = ['name' => 'Anna'];
var_dump(isset($user['name']));
var_dump(isset($user['email']));Output:
bool(true)
bool(false)A default value
More often you want the value right away rather than a check. The ?? operator does it in one line:
<?php
$user = ['name' => 'Anna'];
echo $user['email'] ?? 'not set';Output:
not setA key holding null
isset() returns false for it. array_key_exists() gives the exact answer:
<?php
$user = ['email' => null];
var_dump(isset($user['email']));
var_dump(array_key_exists('email', $user));Output:
bool(false)
bool(true)Functions used in this recipe
- array_key_exists — Checks whether an array has a key.
- isset — Checks that a variable exists and is not null.
- in_array — Checks whether a value exists in an array.