I need to search a multidimensional array for a specific value in any of the indexed subarrays.
In other words, I need to check a single column of the multidimensional array for a value. If the value exists anywhere in the multidimensional array, I would like to return true
otherwise false
$my_array = array( 0 => array( "name" => "john", "id" => 4 ), 1 => array( "name" => "mark", "id" => 152 ), 2 => array( "name" => "Eduard", "id" => 152 ) );
I would like to know the fastest and most efficient way to check if the array $my_array
contains a value with the key "id". For example, if id => 152
anywhere in the multidimensional array, I would like true
.
Nothing will be faster than a simple loop. You can mix-and-match some array functions to do it, but they'll just be implemented as a loop too.
function whatever($array, $key, $val) { foreach ($array as $item) if (isset($item[$key]) && $item[$key] == $val) return true; return false; }
** PHP >= 5.5
simply u can use this
$key = array_search(40489, array_column($userdb, 'uid'));
Let's suppose this multi dimensional array:
$userdb=Array ( (0) => Array ( (uid) => '100', (name) => 'Sandra Shush', (url) => 'urlof100' ), (1) => Array ( (uid) => '5465', (name) => 'Stefanie Mcmohn', (pic_square) => 'urlof100' ), (2) => Array ( (uid) => '40489', (name) => 'Michael', (pic_square) => 'urlof40489' ) ); $key = array_search(40489, array_column($userdb, 'uid'));
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