user3291017
user3291017

Reputation: 47

PHP - using a recursive function to find the max() of nested arrays

The following code uses a simple strategy for finding the max of the nested array. It uses foreach to find and label the max value, however, if I got an array that was nested to MORE than two levels, than my code would be useless. Can anyone please explain to me the idea of a function calling itself for it to find unlimited nested arrays? Would be much appreciated.

Here is my code for example:

<?php
$arr = array("1", "2", array("3", "4"));
foreach($arr as $value){
     if(is_array($value)){
             foreach($value as $value2){
                     $max_array=array($value);
                     // no deeper levels

             }
     } else {
       $max_array=array($value);
     }
}
echo max($max_array);
?>

Upvotes: 1

Views: 1667

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173612

You can use array_walk_recursive() for it:

function array_max_recursive($arr)
{
    $max = -INF;

    array_walk_recursive($arr, function($item) use (&$max) {
        if ($item > $max) {
            $max = $item;
        }
    });

    return $max;
}

echo array_max_recursive(["1", "2", ["3", "4"]]); // 4

Upvotes: 3

Jeroen de Lau
Jeroen de Lau

Reputation: 640

What you want is a recursive function.

The function looks up the biggest element in a an array. If an item in the array is an array, it will find the biggest item in that array and use that to compare.

To find the biggest value in that array it will use the same function.

function findMax($arr){
    $max = 0;
    foreach($arr as $item){
        if(is_array($item)){
            $val = findMax($item);
        }else{
            $val = $item;
        }
        $max  = $val>$max?$val:$max;
    }
    return $max;
 }

Use example:

$arr = Array(1,2,Array(3,10,Array(6,7)));
$arr2 = Array(1,2,Array(3,5,Array(6,7)));
echo findMax($arr)."\n".findMax($arr2);

Result:
10
7

Upvotes: 0

Related Questions