tags:

views:

201

answers:

2

Eg:

$array= array(array(141,151,161),2,3,array(101,202,array(303,606)));

output :606

+1  A: 

What you need is to recursively go through your array ; which means the max function, which is not recursive, will not be "enough".

But, if you take a look at the users's notes on the manual page of max, you'll find this note from tim, who proposes this recursive function (quoting) :

function multimax( $array ) {
    // use foreach to iterate over our input array.
    foreach( $array as $value ) {

        // check if $value is an array...
        if( is_array($value) ) {

            // ... $value is an array so recursively pass it into multimax() to
            // determine it's highest value.
            $subvalue = multimax($value);

            // if the returned $subvalue is greater than our current highest value,
            // set it as our $return value.
            if( $subvalue > $return ) {
                $return = $subvalue;
            }

        } elseif($value > $return) {
            // ... $value is not an array so set the return variable if it's greater
            // than our highest value so far.
            $return = $value;
        }
    }

    // return (what should be) the highest value from any dimension.
    return $return;
}

Using it on your array :

$arr= array(array(141,151,161),2,3,array(101,202,array(303,404)));
$max = multimax($arr);
var_dump($max);

Gives :

int 404

Of course, this will require a bit more testing -- but it should at least be a start.


(Going through the users' notes on manual pages is always a good idea : if you're having a problem, chances are someone else has already had that problem ;-) )

Pascal MARTIN
nit-picky: This version raises an "undefined variable" notice because of $return not being initialized. And `var_dump( multimax(array(0)) );` prints `NULL` instead of `int(0)` for the same reason.
VolkerK
+1  A: 

Same idea as Pascal's solution, only shorter thanks to the Standard PHP Library

$arr= array(array(141,151,161),2,3,array(101,202,array(303,404)));
echo rmax($arr);

function rmax(array $arr) {
  $it = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
  // initialize $max
  $it->next(); $max = $it->current();
  // "iterate" over all values
  foreach($it as $v) {
    if ( $v > $max ) {
      $max = $v;
    }
  }
  return $max;
}
VolkerK
@volkerk thank you :)
Srinivas Tamada