Php get array key by value multidimensional

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

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    In PHP, multidimensional array search refers to searching a value in a multilevel nested array. There are various techniques to carry out this type of search, such as iterating over nested arrays, recursive approaches and inbuilt array search functions.

    Iterative Approach:
    Iterating over the array and searching for significant match is the simplest approach one can follow. Check if an element of the given array is itself an array or not and add the element to the search path, else run array search on the nested array.

    Example:

    function searchForId($search_value, $array, $id_path) {

        foreach ($array as $key1 => $val1) {

            $temp_path = $id_path;

            array_push($temp_path, $key1);

            if(is_array($val1) and count($val1)) {

                foreach ($val1 as $key2 => $val2) {

                    if($val2 == $search_value) {

                        array_push($temp_path, $key2);

                        return join(" --> ", $temp_path);

                    }

                }

            }

            elseif($val1 == $search_value) {

                return join(" --> ", $temp_path);

            }

        }

        return null;

    }

    $gfg_array = array(

        array(

            'score' => '100',

            'name' => 'Sam',

            'subject' => 'Data Structures'

        ),

        array(

            'score' => '50',

            'name' => 'Tanya',

            'subject' => 'Advanced Algorithms'

        ),

        array(

            'score' => '75',

            'name' => 'Jack',

            'subject' => 'Distributed Computing'

        )

    );

    $search_path = searchForId('Advanced Algorithms',

                        $gfg_array, array('$'));

    print($search_path);

    ?>

    Output:

    $ --> 1 --> subject
    

    Recursive Approach:
    In case, when levels of nested arrays increase, it becomes hard to write such programs and debug them. In such cases its better to write a recursive program which can cleanly be written without adding any nested for loops.

    Example:

    function array_search_id($search_value, $array, $id_path) {

        if(is_array($array) && count($array) > 0) {

            foreach($array as $key => $value) {

                $temp_path = $id_path;

                array_push($temp_path, $key);

                if(is_array($value) && count($value) > 0) {

                    $res_path = array_search_id(

                            $search_value, $value, $temp_path);

                    if ($res_path != null) {

                        return $res_path;

                    }

                }

                else if($value == $search_value) {

                    return join(" --> ", $temp_path);

                }

            }

        }

        return null;

    }

    $gfg_array = array(

        "school1" => array(

            "year" => "2017",

            "data" => array(

                'score' => '100',

                'name' => 'Sam',

                'subject' => 'Data Structures'

            )

        ),

        "school2" => array(

            "year" => "2018",

            "data" => array(

                'score' => '50',

                'name' => 'Tanya',

                'subject' => 'Advanced Algorithms'

            )

        ),

        "school3" => array(

            "year" => "2018",

            "data" => array(

                'score' => '75',

                'name' => 'Jack',

                'subject' => 'Distributed Computing'

            )

        )

    );

    $search_path = array_search_id('Jack', $gfg_array, array('$'));

    print($search_path);

    ?>

    Output:

    $ --> school3 --> data --> name
    

    Multidimensional array search using array_search() method:
    The array_search() is an inbuilt function which searches for a given value related to the given array column/key. This function only returns the key index instead of a search path. The array_column() function returns the values from a single column in the input array.

    Example:

    $gfg_array = array(

        array(

            'score'   => '100',

            'name'    => 'Sam',

            'subject' => 'Data Structures'

        ),

        array(

            'score'   => '50',

            'name'    => 'Tanya',

            'subject' => 'Advanced Algorithms'

        ),

        array(

            'score'   => '75',

            'name'    => 'Jack',

            'subject' => 'Distributed Computing'

        )

    );

    $id = array_search('50', array_column($gfg_array, 'score'));

    echo $id;

    ?>

    PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.


    How to Find key value in multidimensional array in PHP?

    Multidimensional array search using array_search() method: The array_search() is an inbuilt function which searches for a given value related to the given array column/key. This function only returns the key index instead of a search path.

    How to get keys of an array in PHP?

    PHP: array_keys() function The array_keys() function is used to get all the keys or a subset of the keys of an array. Note: If the optional search_key_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.
    The main difference between both the functions is that array_search() usually returns either key or index whereas in_array() returns TRUE or FALSE according to match found in search. Value: It specifies the value that needs to be searched in an array.

    How do you check if a value exists in an associative array in PHP?

    The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.