Skip to main content

Multidimensional Array Searching - Find key by specific value

Solution is based on the array_search() function. You need to use PHP 5.5.0 or higher.

$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'
    )
);


Solution-1:
function myfunction($products, $field, $value) {
   foreach($products as $key => $product)
   {
      if ( $product[$field] === $value )
         return $key;
   }
   return false;
}


 

Solution-2:
$key = array_search(40489, array_column($userdb, 'uid')); echo ("The key is: ".$key); //This will output- The key is: 2

The function array_search() has two arguments. The first one is the value that you want to search. The second is where the function should search. The function array_column() gets the values of the elements which key is 'uid'.

Comments