How to find value in multidimensional array PHP

We have done articles related to array filtering by key and value. This article takes a step further and discovers various approaches to find value in multidimensional array PHP. A multidimensional array could be any level deeper, and that is often a challenge when we have to find a value that resides deep within an array.

There are two approaches to go about this problem: Iterative and Recursive. The iterative approach uses nested loops to iterate over the levels of arrays but the approach soon becomes inefficient if there are more than two levels.

The second approach is recursive which is based on the concept of recursion in programming. Recursion involves a function that calls itself over and over to perform repetitive tasks. The recursive approach comes in handy because you don’t have to worry about the number of levels in an array.

In this article, we’ll cover both of these approaches. We will be using an associative array that represents a player entity in a video game. Here’s how the array looks like.

$players_arr = [
0 => array(
    "Name" => "Blob202",
    "Rank" => "Platinum",
    "Standings" => array(
        "2016" => "1002",
        "2017" => "715",
        "2018" => "514",
        "2019" => "302",
        "2020" => "98",
        "2021" => "54"),
    "Tournaments" => array(
        0 => array("TournamentName"=>"SummerFestival2k16","Position"=>5),
        1 => array("TournamentName"=>"SpringFestival2k20","Position"=>3)), 
 
    ),
1 => array(
        "Name" => "Karen101",
        "Rank" => "Gold",
        "Standings" => array(
            "2016" => "1010",
            "2017" => "600",
            "2018" => "520",
            "2019" => "431",
            "2020" => "202",
            "2021" => "100"),
         
        "Tournaments" => array(
            0 => array("TournamentName"=>"AutumnFestival2k20","Position"=>1),
            1 => array("TournamentName"=>"WinterFestival2k20","Position"=>2)),      
        ),    
2 => array(
        "Name" => "Bond007",
        "Rank" => "Platinum",
        "Standings" => array(
            "2016" => "1000",
            "2017" => "500",
            "2018" => "316",
            "2019" => "212",
            "2020" => "65",
            "2021" => "1"),
        ),
        "Tournaments" => array(
            0 => array("TournamentName"=>"Quarantine2k19","Position"=>10),
            1 => array("TournamentName"=>"SummerFestival2k17","Position"=>2))      
];

The maximum depth is three here. This array is ideal to cover different cases and apply the right approach to search in multidimensional array in PHP.

#1 – Find value in multidimensional array PHP using iterative approach

We will see an iterative approach based on a query. First, we will resolve a query that would require at most two nested foreach loops, and then we will see a query that would require more than two nested foreach loops. At that point, we’ll discuss how the recursive approach is more efficient and handy than increasing nested loops.

find value in multidimensional array PHP

Query#1 – Yearly Standings

Here’s the first query:

“Find yearly standings of the players”

This query requires us to iterate over the array and accumulate standings of every player in a much neater fashion. We will require two nested loops here. Remember that we have mentioned in the beginning that two nested loops aren’t a bad option at all. So, let’s solve this problem using the iterative approach.
Here’s the code.

//This array will hold the player names and standings.
$playerstandings_arr = [];
//Iterate over the first level.
foreach($players_arr as $player)
{
    //Player names become key values and the value is an array of standings.
    $playerstandings_arr[$player["Name"]] = [];
 
    //Iterate over the standings that is level two array.
    foreach($player["Standings"] as $year=>$standings){
        $playerstandings_arr[$player["Name"]][$year] = $standings;
    }
}
 
print_r($playerstandings_arr);

The first loop iterates over player entities and the second loop iterates over the standings to find yearly standings and pass them on to the right player in the resulting array. 

Here’s the output.

Array
(
    [Blob202] => Array    
        (
            [2016] => 1002
            [2017] => 715 
            [2018] => 514 
            [2019] => 302 
            [2020] => 98  
            [2021] => 54  
        )

    [Karen101] => Array   
        (
            [2016] => 1010
            [2017] => 600 
            [2018] => 520 
            [2019] => 431 
            [2020] => 202 
            [2021] => 100 
        )

    [Bond007] => Array    
        (
            [2016] => 1000
            [2017] => 500 
            [2018] => 316 
            [2019] => 212 
            [2020] => 65
            [2021] => 1
        )

)

That was a relatively simpler query as we had only two levels to loop through. Let’s see a query that makes the iterative approach inefficient.

Query#2 – Quarantine2k19 Tournament

Here’s a more complex query : 

Find players who took part in the Quarantine2k19 tournament”

This query requires more than two nested loops. Consequently, the code becomes inefficient and code structure becomes difficult to read due to congested nesting. We are about to show you the iterative approach just to draw a contrast with a recursive approach that we would do for this query later on.

//Iterate over the first level.
foreach($players_arr as $player)
{
 
    //Iterate over the tournaments that is level two array.
    foreach($player["Tournaments"] as $key=>$tournament){
        //Iterate over each tournament array that is level three array.
        foreach($tournament as $key=>$value)
        {
            if($value == "Quarantine2k19")
            {
                echo "Player: ".$player["Name"]." took part in the Quarantine2k19 tournament";
            }
        }
    }
}
 
//OUTPUT
//Player: Bond007 took part in the Quarantine2k19 tournament

Guess what if we have more than three levels. You can see that the code already got messier, adding any more nested loops will make it even ugly. So, what’s the way out? The answer is the recursive approach to search in multidimensional array in PHP.

#2 – Find value in multidimensional array PHP using recursive approach

find value in multidimensional array PHP

We’ll try to redo the code for Query#2 in the previous section. However, we’ll be using a recursive approach this time.

“Find players who took part in the Quarantine2k19 tournament”


The recursive approach involves a function that does a repetitive task by calling itself over and over. Let’s see that in practice in the code.

function recursiveFunc($arr,$player_name = null)
{
    
    foreach($arr as $key=>$value)
    {  
        if($key == "Name")
        {
            $player_name = $value;
        }
 
        if(gettype($value) == "array")
        {
            //If array within array then recall the function.
            recursiveFunc($value,$player_name);
        }
 
        if($value == "Quarantine2k19")
        {
            echo "Player: ".$player_name." took part in the Quarantine2k19 tournament";
        }
    }
}
 
//Call the function.
recursiveFunc($players_arr);
 
//OUTPUT
//Player: Bond007 took part in the Quarantine2k19 tournament

So, the function defined here is customised to the query here. It takes the array and iterates through it using a loop. However, it only uses a single foreach loop even then it reaches the max depth. How?

The answer is : Recursion. Notice that the function calls itself when there is an array within an array and applies the same logic over and over until it find value in multidimensional array PHP. Recursion is a tricky concept whatsoever but with practice you’ll definitely master it.

One great advantage of recursion is that you won’t be concerned about the exact depth of the array which is otherwise a huge concern in the iterative approach because you have to have the same number of nested loops as the levels you want to reach out to.

That being said we have pretty much seen the two contrasting approaches to search in multidimensional array in PHP

Conclusion

We have seen two contrasting approaches to find value in multidimensional array PHP. The first approach is the iterative approach that uses nested loops to dive deep into a multidimensional array. However, this approach quickly becomes inefficient when we have more than two nested loops. In contrast, the recursive approach uses recursion to access the deepest levels in a multidimensional array while relieving the concern for the number of levels in a multidimensional array. 

We hope you have enjoyed the article. Stay tuned for more exciting and informative content related to PHP. 

Want to explore more useful PHP tutorials?

We have many fun articles related to PHP. You can explore these to learn more about PHP.

How to read and convert CSV to associative array PHP

Search for multiple values in PHP array

How to filter array of objects by value in PHP


Article Categories

Article Tags

© 2022 Confident.Systems