1

I have a situation where I want to check for a key 2 levels deep in a PHP array. So my code currently looks like...

    if(array_key_exists($needleBox, $haystack)) {
        if(array_key_exists($needle, $haystack[$needleBox])) {
            // do stuff with value attached to $needle
        }
    }

Where I first check for the array containing my needle ($needleBox), then check for the needle if $needleBox is found.

Is it safe to skip the check for $needleBox & use...

    if(array_key_exists($needle, $haystack[$needleBox])) {
        // do stuff with value attached to $needle
    }

or to check for both together in one if statement like...

    if(array_key_exists($needleBox, $haystack) && array_key_exists($needle, $haystack[$needleBox])) {
        // do stuff with value attached to $needle
    }

I consider the first alternative preferable for being more concise.

1
  • 1
    First alternative will throw a warning if that key doesn't exist so you will need to suppress that (using @). Commented Apr 21, 2018 at 4:24

1 Answer 1

3

why dont you use isset. which i much more prefer it.. isset is much faster than array_key_exists. BTW isset will return false if the value is null..

if (isset($haystack[$needleBox]) && isset($haystack[$needleBox][$needle])) {
     //code
}

OR

if ($haystack[$needleBox][$needle] ?? null)) {
     //code
}

EDIT agreed with @shawn advise

if (isset($haystack[$needleBox][$needle])) {
     //code
}
Sign up to request clarification or add additional context in comments.

4 Comments

I like that, & will accept the answer as soon as allowed. Thank you.
You do NOT need to repeat the key check. just write isset($haystack[$needleBox][$needle]) is OK
Agreed with @shawn. If $haystack[$needleBox][$needle] is set it means $haystack[$needleBox] is also set
This answer, & the comments, have me thinking I've been using array_key_exists in a lot of situations where isset would be more appropriate.

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.