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];

1 Answer 1


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


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.