2
\$\begingroup\$

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];
asked Jun 19, 2018 at 8:54
\$\endgroup\$
0

1 Answer 1

12
\$\begingroup\$

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

answered Jun 19, 2018 at 9:20
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.