Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a deep array value is present

Tags:

php

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

like image 825
Chris Burgess Avatar asked May 07 '09 00:05

Chris Burgess


People also ask

How do you check if a value exists in a multidimensional array?

Multidimensional array search using array_search() method: The array_search() is an inbuilt function which searches for a given value related to the given array column/key. This function only returns the key index instead of a search path.

How do you check if an array is an IF value?

It would look something like this: $statuses = [1, 7, 8, 7]; if (in_array(1, $statuses) || in_array(3, $statuses) || in_array(6, $statuses) || in_array(8, $statuses) || in_array(9, $statuses)) { // Do something } else { // Do something else } // etc...

How do you check if a value exists in an array PHP?

The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.


1 Answers

The following will work as you expect:

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

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

like image 134
James Emerton Avatar answered Sep 22 '22 00:09

James Emerton