2

if one is uncertain whether an array index exists, he normally does something like

if (isset($array[$key]))
    $val = $array[$key];

for large arrays, is it faster to not do this look up two times?

If yes, how would one go about doing this in one look up?

4
  • $val = $array[$key] ?? null;? Commented Jan 3, 2020 at 9:35
  • @Jeto doesnt that throw an error if key does not exist? Commented Jan 3, 2020 at 9:36
  • It does not: 3v4l.org/572Zk. See null coalescing operator. Commented Jan 3, 2020 at 9:38
  • @Jeto looks like you have an answer Commented Jan 3, 2020 at 9:42

1 Answer 1

1

You may use the null-coalescing operator:

$val = $array[$key] ?? null;

which is equivalent to:

$val = isset($array[$key]) ? $array['key'] : null;

The only minor difference is that $val gets defined no matter what (to null), where in your original code it would stay undefined if you don't have an else.

I can't say for sure that it executes faster, but it's definitely handier/cleaner to write/maintain (since you don't write the same $array[$key] part twice within the statement).

Demo: https://3v4l.org/mtG7S

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.