21

I want to quickly identify if a key is present in an array, to avoid throwing an error.

For example, I might have an array like this

$arr['f']['b']['g'] = array( 'a', 'b', 'c', ) ;

Or the array might not have any variables in $arr['f']['b'] at all:

$arr['f']['x'] = array() ;

How can I avoid repetition in a test when referencing the (perhaps) contents of $arr['f']['b']['g']?

if ( isset( $arr['f'] ) &&
     isset( $arr['f']['b'] ) &&
     isset( $arr['f']['b']['g'] ) /* ... yawn */ ) {
  /* blah */
}

There must be a terser way to identify whether a given array value I'm referencing exists? It seems far too verbose to have to test for the presence of both the value I seek, and all its ancestry as well. In some circumstances that makes sense, yes, but not all.

By example: it might represent, say, user->session->cart, where I want a way to quickly check whether the cart has entries, without having to include a check each for whether the user exists, then whether the session exists, then whether the cart exists, then ...

Edit: I'm not looking for "does an array value with a key name of 'g' exist", as "does an array value with an ancestry of f => b => g exist".

2 Answers 2

41

The following will work as you expect:

if(isset($a['a']['b']['c']))

If any of those elements are undefined, isset() will return false.

4
  • 3
    Just to clarify, this also safely tests the existence of $a: it returns false if $a is not set. Sep 7, 2015 at 0:40
  • 3
    Wow, was sure for years that this does not work. Lol.
    – baldrs
    Oct 9, 2017 at 14:11
  • Is isset($array[$property]) always better than array_key_exists($property, $array) ? Nov 8, 2017 at 12:09
  • 1
    @dev.mnr.j isset() is more performant. And isset gives you false if the array key exists but the value is null.
    – fabpico
    Jan 4, 2018 at 13:16
-1

In the comments of array_search they have code for multi dimensional search. It might help.

1
  • Thanks for the reply. There are over a dozen example code blocks on that page (more, I didn't count), but I can't see which one of them which would provide a solution that would be efficient (either in terms of terseness, or performance). Will update question to clarify what I'm after. Thanks again! May 7, 2009 at 0:36

Your Answer

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

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