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".
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.
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...
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.
The following will work as you expect:
if(isset($a['a']['b']['c']))
If any of those elements are undefined, isset()
will return false.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With