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
🌐
PHP
php.net › manual › en › function.array-values.php
PHP: array_values - Manual
This is another way to get value from a multidimensional array, but for versions of php >= 5.3.x <?php /** * Get all values from specific key in a multidimensional array * * @param $key string * @param $arr array * @return null|string|array */ function array_value_recursive($key, array $arr){ $val = array(); array_walk_recursive($arr, function($v, $k) use($key, &$val){ if($k == $key) array_push($val, $v); }); return count($val) > 1 ?
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;
}
Discussions

How To Find The Position Of A Key In A Multidimensional Array?
Off the top of my head, it seems you'll have to do the array_keys() and see if it's in there, although there's also array_key_exists(). if the key isn't there, then do foreach() to look at each of those elements'. If there's always exactly nested levels, it's not too bad. If it's a variable number of levels, you'll probably have to use a recursive function. You should also be able to use array_filter() with a custom function. There could be complications, like if more than one entry had that key, or if the key's value is an array. More on reddit.com
🌐 r/PHPhelp
3
1
July 1, 2023
Multidimensional arrays - Getting a value without loops - PHP - SitePoint Forums | Web Development & Design Community
Hi, I have an array like the following: $array = array( 0 => array( 'user' => 1, 'name' => 'Name 1', ), 1 => array( 'user' => 2, 'name' => 'Name 2', ), 2 => array( 'user' => 3, 'name' => 'Name 3', ), ); I want to get the name value from the above array for given user value, but without using ... More on sitepoint.com
🌐 sitepoint.com
0
October 5, 2018
php - How to get an array of specific "key" in multidimensional array without looping - Stack Overflow
Your first example will not return an array, just the last value found for $user['name'] in the array. You need to push/append to the $carry and return the $carry as you go. 2019-12-08T21:20:00.58Z+00:00 ... Find the answer to your question by asking. More on stackoverflow.com
🌐 stackoverflow.com
PHP multidimensional array get value by key - Stack Overflow
The real array I have is quite large and the keys are all at different positions. I've started to write a bunch of nested foreach and if/isset but it's not quite working and feels a bit 'wrong'. I'm fairly familiar with PHP but a bit stuck with this one. Is there a built in function or a best practise way that I can access all values based on the key name regardless of where it is. E.g get all values from ... More on stackoverflow.com
🌐 stackoverflow.com
November 9, 2015
🌐
ItSolutionstuff
itsolutionstuff.com › post › how-to-get-specific-key-value-from-multidimensional-array-in-phpexample.html
How to Get Specific Key Value from Multidimensional Array PHP? - ItSolutionstuff.com
May 14, 2024 - we almost require to get specific key and value in array when work with php multidimensional array. like if you have one multidimensional array with each array with id, name, email etc key. You need to get only all name from array then how you can get it?, i will show you how we can do it.
🌐
GeeksforGeeks
geeksforgeeks.org › php › how-to-search-by-keyvalue-in-a-multidimensional-array-in-php
How to search by key=&gt;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)) ...
🌐
GitHub
gist.github.com › 53a9b4e85cfc460eb6c22346ceb68f01
Get all values from specific key in a multidimensional array, similar to array_columns · GitHub
Get all values from specific key in a multidimensional array, similar to array_columns - array-value-recursive.php
🌐
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.

Find elsewhere
🌐
Quora
quora.com › How-do-I-fetch-the-key-value-from-a-multidimensional-array
How to fetch the key value from a multidimensional array - Quora
Below are concise, language-agnostic ... (PHP, JavaScript, Python) plus techniques for searching by key or by value. ... Multidimensional array = array whose elements may themselves be arrays (nested dictionaries/maps). ... Given a path (sequence of keys/indices), get the value ...
🌐
Quora
quora.com › Learning-PHP-Is-there-a-way-to-get-the-value-of-multi-dimensional-array-by-specifying-the-key-with-a-variable
Learning PHP: Is there a way to get the value of multi-dimensional array by specifying the key with a variable? - Quora
Answer (1 of 14): [code]$key = '["a"]["b"]'; echo $array{$key} [/code]will not and should not work. This will work, but I’m not clear on exactly what you’re trying to do, so this may not be the best answer either: [code]$one = $_REQUEST["user_input_value_for_a"]; $two = $_REQUEST["user...
🌐
Koding Made Simple
kodingmadesimple.com › 2015 › 12 › search-multidimensional-array-for-key-value-php.html
Search Multidimensional Array for Key Value in PHP
The function array_column() returns the values of the specified column from the array. That explains about searching multidimensional array for key and value in php language. ... Thanks for splitting your comprehension with us. PHP- It’s an open source server-side scripting language particularly ...
🌐
SitePoint
sitepoint.com › php
Multidimensional arrays - Getting a value without loops - PHP - SitePoint Forums | Web Development & Design Community
October 5, 2018 - Hi, I have an array like the following: $array = array( 0 => array( 'user' => 1, 'name' => 'Name 1', ), 1 => array( 'user' => 2, 'name' => 'Name 2', ), 2 => array( 'user' => 3, 'name' => 'Name 3', ), …
🌐
sebhastian
sebhastian.com › php-search-multidimensional-array
PHP how to search multidimensional array with key and value | sebhastian
November 2, 2022 - Suppose you have a multidimensional ... => "Michael", "age" => 30, ], ]; To search the array by its value, you can use the foreach statement....
🌐
ItSolutionstuff
itsolutionstuff.com › post › php-multidimensional-array-search-by-value-exampleexample.html
PHP Multidimensional Array Search By Value Example - ItSolutionstuff.com
May 14, 2024 - I’m going to show you about php multidimensional array search key by value. We will look at example of how to search value in multidimensional array in php. Let's get started with how to search by key= value in a multidimensional array in php. If you need to get find value from multidimensional array in php.
🌐
Javatpoint
javatpoint.com › php-multidimensional-array-search-by-value
PHP Multidimensional Array Search By Value - javatpoint
PHP The is a built-in function of PHP that dumps the information about the variables. This information includes the data type and value of the variable. In case of string, it also includes the size of the string passed inside the function. The array and object...
🌐
Stack Overflow
stackoverflow.com › questions › 63562426 › get-array-key-with-value-in-a-multidimensional-array
php - Get array key with value in a multidimensional array - Stack Overflow
August 24, 2020 - Even if the use of the more fancy array functions still eludes you yet, getting this done by simply looping over the data should be a trivial excercise. ... Save this answer. ... Show activity on this post. You can loop and look for a value. Here the first Bob's age is found. <?php $people = [ ['Bob', '76'], ['Allison','52'] ]; $result = null; foreach($people as list($name, $age)) { if($name == 'Bob') { $result = $age; break; } } var_dump($result);