1

Hi anybody can help me to find the maximum value of the array that are given in the below . i expect the result of 650 is the maximum value....

$my_array = array(array(128,300,140)10,15,array(130,array(500,650))); 
hakre
  • 193,403
  • 52
  • 435
  • 836
krishna
  • 11
  • 1

7 Answers7

3

Here you go, using RecursiveArrayIterator in 3 readable lines of code:

$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$flattenedArray = iterator_to_array($it);
$max = max($flattenedArray);

Or, if you want to not flatten (and copy), but prefer to iterate (uses far less memory, but slower):

$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$max = 0;
foreach ($it as $value) {
    $max = max($value, $max);
}
ircmaxell
  • 163,128
  • 34
  • 264
  • 314
1

Flatten the array, then call max() on it. The return value of max() should be 650 from your example.

Delan Azabani
  • 79,602
  • 28
  • 170
  • 210
1

Also possible is

$data = array(array(128,300,140),10,15,array(130,array(500,650)));
$max = 0;
array_walk_recursive(
    $data,
    function($val) use (&$max) {
        if($val > $max) $max = $val;
    }
);
echo $max; // 650
Gordon
  • 312,688
  • 75
  • 539
  • 559
0

You could also do it recursively, if the item is an array, call the function again to return the max item from that array.

In the end you should have always the max item and then in the last iteration, you could call the max from those results.

Ólafur Waage
  • 68,817
  • 22
  • 142
  • 198
0

This does the trick:

function flatten($ar) {
    $toflat = array($ar);
    $res = array();
    while (($r = array_shift($toflat)) !== NULL) {
        foreach ($r as $v) {
            if (is_array($v)) {
                $toflat[] = $v;
            } else {
                $res[] = $v;
            }
        }
    }
    return $res;
}

$arr = array(array(128,300,140),10,15,array(130,array(500,650)));
echo max(array_flatten($arr));

EDIT: Updated flatten array with the one at How to "flatten" a multi-dimensional array to simple one in PHP?

Community
  • 1
  • 1
TuteC
  • 4,342
  • 30
  • 40
0
<?php
$my_array = array(array(128,300,140),10,15,array(130,array(500,650)));

function findLargest($arr) {
    $largest = 0;
    foreach ($arr as $item) {
        if (is_array($item)) {
            $item = findLargest($item);
        }
        if ($item > $largest) {
            $largest = $item;
        }
    }
    return $largest;
}

echo "Largest is ".findLargest($my_array)."\n";

?>
qbert220
  • 11,220
  • 4
  • 31
  • 31
0
function maximum($in)
{
  if (!is_array($in)) $max = $in;
  else foreach ($in as $element) 
  {
    $elementMax = maximum($element);
    if (isset($max)) $max = max($elementMax, $max); else $max = $elementMax;
  }

  return $max;
}
borrible
  • 17,120
  • 7
  • 53
  • 75