tags:

views:

192

answers:

2

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".

A: 

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

Ólafur Waage
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!
Chris Burgess
+3  A: 

The following will work as you expect:

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

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

James Emerton
Huh! Well spotted :)
Chris Burgess