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

Example

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

echo ("The key is: ".$key);
//This will output- The key is: 2

Explanation

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'`.

Summary

So you could use it as:
array_search('breville-one-touch-tea-maker-BTM800XL', array_column($products, 'slug'));

or, if you prefer:

// define function
function array_search_multidim($array, $column, $key){
    return (array_search($key, array_column($array, $column)));
}

// use it
array_search_multidim($products, 'slug', 'breville-one-touch-tea-maker-BTM800XL');

The original example(by xfoxawy) can be found on the DOCS.
The array_column() page.


Update

Due to Vael comment I was curious, so I made a simple test to meassure the performance of the method that uses array_search and the method proposed on the accepted answer.

I created an array which contained 1000 arrays, the structure was like this (all data was randomized):

[
      {
            "_id": "57fe684fb22a07039b3f196c",
            "index": 0,
            "guid": "98dd3515-3f1e-4b89-8bb9-103b0d67e613",
            "isActive": true,
            "balance": "$2,372.04",
            "picture": "http://placehold.it/32x32",
            "age": 21,
            "eyeColor": "blue",
            "name": "Green",
            "company": "MIXERS"
      },...
]

I ran the search test 100 times searching for different values for the name field, and then I calculated the mean time in milliseconds. Here you can see an example.

Results were that the method proposed on this answer needed about 2E-7 to find the value, while the accepted answer method needed about 8E-7.

Like I said before both times are pretty aceptable for an application using an array with this size. If the size grows a lot, let's say 1M elements, then this little difference will be increased too.

Update II

I've added a test for the method based in array_walk_recursive which was mentionend on some of the answers here. The result got is the correct one. And if we focus on the performance, its a bit worse than the others examined on the test. In the test, you can see that is about 10 times slower than the method based on array_search. Again, this isn't a very relevant difference for the most of the applications.

Update III

Thanks to @mickmackusa for spotting several limitations on this method:

  • This method will fail on associative keys.
  • This method will only work on indexed subarrays (starting from 0 and have consecutively ascending keys).

Note on Update III

  • not taking performance into account: you can use array_combine with array_keys & array_column to overcome this limitation in a one-liner like:
$product_search_index = 
array_search( 'breville-one-touch-tea-maker-BTM800XL', array_filter( array_combine( array_keys($products), array_column( $products, 'slug' ) ) ) );
Answer from Iván Rodríguez Torres on Stack Overflow
Top answer
1 of 10
235

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

Example

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

echo ("The key is: ".$key);
//This will output- The key is: 2

Explanation

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'`.

Summary

So you could use it as:
array_search('breville-one-touch-tea-maker-BTM800XL', array_column($products, 'slug'));

or, if you prefer:

// define function
function array_search_multidim($array, $column, $key){
    return (array_search($key, array_column($array, $column)));
}

// use it
array_search_multidim($products, 'slug', 'breville-one-touch-tea-maker-BTM800XL');

The original example(by xfoxawy) can be found on the DOCS.
The array_column() page.


Update

Due to Vael comment I was curious, so I made a simple test to meassure the performance of the method that uses array_search and the method proposed on the accepted answer.

I created an array which contained 1000 arrays, the structure was like this (all data was randomized):

[
      {
            "_id": "57fe684fb22a07039b3f196c",
            "index": 0,
            "guid": "98dd3515-3f1e-4b89-8bb9-103b0d67e613",
            "isActive": true,
            "balance": "$2,372.04",
            "picture": "http://placehold.it/32x32",
            "age": 21,
            "eyeColor": "blue",
            "name": "Green",
            "company": "MIXERS"
      },...
]

I ran the search test 100 times searching for different values for the name field, and then I calculated the mean time in milliseconds. Here you can see an example.

Results were that the method proposed on this answer needed about 2E-7 to find the value, while the accepted answer method needed about 8E-7.

Like I said before both times are pretty aceptable for an application using an array with this size. If the size grows a lot, let's say 1M elements, then this little difference will be increased too.

Update II

I've added a test for the method based in array_walk_recursive which was mentionend on some of the answers here. The result got is the correct one. And if we focus on the performance, its a bit worse than the others examined on the test. In the test, you can see that is about 10 times slower than the method based on array_search. Again, this isn't a very relevant difference for the most of the applications.

Update III

Thanks to @mickmackusa for spotting several limitations on this method:

  • This method will fail on associative keys.
  • This method will only work on indexed subarrays (starting from 0 and have consecutively ascending keys).

Note on Update III

  • not taking performance into account: you can use array_combine with array_keys & array_column to overcome this limitation in a one-liner like:
$product_search_index = 
array_search( 'breville-one-touch-tea-maker-BTM800XL', array_filter( array_combine( array_keys($products), array_column( $products, 'slug' ) ) ) );
2 of 10
176

Very simple:

function myfunction($products, $field, $value)
{
   foreach($products as product)
   {
      if ( $product[$field] === $value )
         return $key;
   }
   return false;
}
🌐
GeeksforGeeks
geeksforgeeks.org › php › how-to-search-by-keyvalue-in-a-multidimensional-array-in-php
How to search by key=>value in a multidimensional array in PHP ? - GeeksforGeeks
July 15, 2024 - ... <?php // PHP program to carry out multidimensional array // search by key=>value // Function to recursively search for a // given key=>value function search($array, $key, $value) { $results = array(); // if it is array if (is_array($array)) ...
Top answer
1 of 16
238

Code:

function search($array, value)
{
    $results = array();

    if (is_array($array)) {
        if (isset($array[$key]) && $array[value) {
            $results[] = $array;
        }

        foreach ($array as $subarray) {
            $results = array_merge($results, search($subarray, value));
        }
    }

    return $results;
}

$arr = array(0 => array(id=>1,name=>"cat 1"),
             1 => array(id=>2,name=>"cat 2"),
             2 => array(id=>3,name=>"cat 1"));

print_r(search($arr, 'name', 'cat 1'));

Output:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => cat 1
        )

    [1] => Array
        (
            [id] => 3
            [name] => cat 1
        )

)

If efficiency is important you could write it so all the recursive calls store their results in the same temporary $results array rather than merging arrays together, like so:

function search($array, value)
{
    $results = array();
    search_r($array, value, $results);
    return $results;
}

function search_r($array, value, &$results)
{
    if (!is_array($array)) {
        return;
    }

    if (isset($array[$key]) && $array[value) {
        $results[] = $array;
    }

    foreach ($array as $subarray) {
        search_r($subarray, value, $results);
    }
}

The key there is that search_r takes its fourth parameter by reference rather than by value; the ampersand & is crucial.

FYI: If you have an older version of PHP then you have to specify the pass-by-reference part in the call to search_r rather than in its declaration. That is, the last line becomes search_r($subarray, value, &$results).

2 of 16
78

How about the SPL version instead? It'll save you some typing:

// I changed your input example to make it harder and
// to show it works at lower depths:

$arr = array(0 => array('id'=>1,'name'=>"cat 1"),
             1 => array(array('id'=>3,'name'=>"cat 1")),
             2 => array('id'=>2,'name'=>"cat 2")
);

//here's the code:

    $arrIt = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));

 foreach ($arrIt as $sub) {
    $subArray = $arrIt->getSubIterator();
    if ($subArray['name'] === 'cat 1') {
        $outputArray[] = iterator_to_array($subArray);
    }
}

What's great is that basically the same code will iterate through a directory for you, by using a RecursiveDirectoryIterator instead of a RecursiveArrayIterator. SPL is the roxor.

The only bummer about SPL is that it's badly documented on the web. But several PHP books go into some useful detail, particularly Pro PHP; and you can probably google for more info, too.

🌐
TutorialsPoint
tutorialspoint.com › how-to-search-by-key-value-in-a-multidimensional-array-in-php
How to Search by key=value in a Multidimensional Array in PHP
Here's an example of using array_filter() and array_column() to search for a key-value pair in a multidimensional array in PHP:
🌐
PHP
php.net › manual › en › function.array-search.php
PHP: array_search - Manual
For a better performance, you could do; <?php $colors = array_column($people, 'fav_color'); $found_key = array_search('blue', $colors); ?> ... If you are using the result of array_search in a condition statement, make sure you use the === operator instead of == to test whether or not it found a match. Otherwise, searching through an array with numeric indicies will result in index 0 always getting evaluated as false/null.
🌐
Reddit
reddit.com › r/phphelp › how to find the position of a key in a multidimensional array?
r/PHPhelp on Reddit: How To Find The Position Of A Key In A Multidimensional Array?
July 1, 2023 -

I am querying data from an API and the return result is very cumbersome to deal with.

It's a multidimensional array but the indexes are a mix of keys and ints. Like

$result[0]['keyValueX'][0]['keyValueY']

And it's possible that using another type of query will yield the result in a different order of indexes:

$result['keyValueB'][0]['keyValueX']

But what I'm interested in, is knowing if the result has a particular key that exists somewhere deep within it. At any level. And if it does exist, just return the value that is associated with that key......instead of me having to type out all these indexes just to reach that place.

What's the way to do this? I have tried

array_keys($result)

but when I do that, it only gives me the first level of keys that exist. On the outermost level. It does not go deeper in.

🌐
Koding Made Simple
kodingmadesimple.com › 2015 › 12 › search-multidimensional-array-for-key-value-php.html
Search Multidimensional Array for Key Value in PHP
<?php // php function to search multi-dimensional array function searchArray($key, $st, $array) { foreach ($array as $k => $v) { if ($v[$key] === $st) { return $k; } } return null; } // define multidimensional array $color = Array ( ('r') => Array ( ('red') => 255, ('green') => 0, ('blue') ...
🌐
Morioh
morioh.com › p › 99b33b04e0a8
PHP Multidimensional Array Search by Key and Value with Examples
In this article, we would love to shows, how you can create your own function for searching PHP Multidimensional Array. Here we will take two examples for searching in the multidimensional array using custom created function.
Find elsewhere
🌐
sebhastian
sebhastian.com › php-search-multidimensional-array
PHP how to search multidimensional array with key and value | sebhastian
November 2, 2022 - In PHP 5.5 and above, you can also use the array_search() function combined with the array_column() function to find an array that matches a condition. ... Let’s create a custom function from the search code so that you can perform a more ...
🌐
Javatpoint
javatpoint.com › php-multidimensional-array-search-by-value
PHP Multidimensional Array Search By Value - javatpoint
PHP Multidimensional Array Search By Value with examples, php file, php session, php date, php array, php form, functions, time, xml, ajax, php mysql, regex, string, oop, addslashes(), addcslashes() etc.
🌐
GeeksforGeeks
geeksforgeeks.org › php › php-multidimensional-array-search-by-value
PHP multidimensional array search by value - GeeksforGeeks
July 11, 2025 - <?php // PHP program to carry out multidimensional array search // Function to iteratively search for a given value function searchForId($search_value, $array, $id_path) { // Iterating over main array foreach ($array as $key1 => $val1) { $temp_path ...
🌐
GitHub
gist.github.com › bc057772ee7e6ebace78
search key=>value pair in Multidimensional Array in PHP · GitHub
search key=>value pair in Multidimensional Array in PHP - search key=>value pair in Multidimensional Array PHP.php
🌐
SitePoint
sitepoint.com › php
Best way to do array_search on multi-dimensional array? - PHP - SitePoint Forums | Web Development & Design Community
May 23, 2012 - ... function array_find_deep($array, $search, $keys = array()) { foreach($array as $key => $value) { if (is_array($value)) { $sub = array_find_deep($value, $search, array_merge($keys, array($key))); if (count($sub)) { return $sub; } } elseif ...
🌐
Atcodex
atcodex.com › home › php multidimensional array search by key and value with examples
PHP Multidimensional Array Search by Key and Value with Examples
August 28, 2021 - Sometimes we need to search in ... array by key or value without using any function. This tutorial shows you, the fastest way to search in a multidimensional array. In this article, we would love to shows, how you can create your own function for searching Multidimensional Array. Here we will take two examples for searching in the multidimensional array using the custom created function. Sometimes we need to integrate a multidimensional array search by value in php...
🌐
Experts Exchange
experts-exchange.com › questions › 27653578 › search-multidimensional-array-by-key-and-return-array-value's-as-result.html
Solved: search multidimensional array by key and return array value's as result | Experts Exchange
November 13, 2010 - http://php.net/manual/en/function.array-key-exists.php · Select allOpen in new window · ScottNL1 · ASKER · i am aware of this function, but it does not search in multidimensional array's and it does not return the array values. array_key_exists("item_id" ,$array); will return false.