Given is an array $array
and a key $key
. If the array has the key, then I want to return the value, otherwise null. Is there a better way in PHP7 now, then doing it like that:
return (empty($array[$key])) ? null : $array[$key];
For the question title, there indeed a null coalescing operator introduced in PHP7:
return $array[$key] ?? null;
which is a shorthand for
return (isset($array[$key])) ? $array[$key] : null;
however, in your code you are using empty()
which is different from isset() and for this code there is no shorthand in PHP.
with empty(), your code will also return null if $array[$key]
exists but contains an empty-like value, like false
, 0, empty array and such