0

I am creating a function that will lookup for the maximum value within an array. However, say I have this example,

function MaxArray($arr)
{
    return max($arr);
}
$arr = array(array(141,151,161), 2, 3, array(101, 202, array(303,404)));
print_r(MaxArray($arr));

This will return values Array ( [0] => 141 [1] => 151 [2] => 161 )

What I want for an output is to get 404 because it is the highest value in the array. Any insights? Thanks.

1
  • 1
    flatten the array first. Commented Dec 17, 2011 at 4:31

2 Answers 2

2

As a modification of your function

function MaxInArray ($arr) {
    $m = NULL;
    foreach ($arr as $v) {
        if (is_array($v)) $v = MaxInArray($v);
        if (is_null($m) || $v > $m) $m = $v;
    }
    return $m;
}

Made it recursive.

Sign up to request clarification or add additional context in comments.

Comments

0

PHP has many features built-in to flatten or recursively walk the array, e.g. array_walk_recursiveDocs. For example combine with an anonymous functionDocs this can be solved with some little code:

array_walk_recursive($arr, function($v) use(&$max) {$max = max($v, $max);});

var_dump($max); # int(404)

Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.