Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a specific value exists at a specific key in any subarray of a multidimensional array

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.

like image 692
Rob Avatar asked Aug 09 '11 02:08

Rob


2 Answers

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; } 
like image 133
Dan Grossman Avatar answered Sep 20 '22 18:09

Dan Grossman


** 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')); 
like image 41
Manuel Pardo Avatar answered Sep 21 '22 18:09

Manuel Pardo