Mohammad Faisal Islam
Mohammad Faisal Islam

Reputation: 507

Finding maximum value from an array which contains positive integers and/or recursively nested arrays of positive integers

If an array initialized as:

   $arr = array(array(141,151,161),2,3,array(101,102,array(303,404,606,555,789,array(1000,22,9999,array(9057,100000),522))));

Then the result should be: 100000

I have written a function to solve this problem but I need less bytes and less memory of codes.

My Function is:

function MaxArray($arr){
$length = count($arr);
global $maxValue;
for($i=0;$i<$length;$i++){
        if(is_int($arr[$i])){

                if($maxValue < $arr[$i]){
                    $maxValue = $arr[$i];
                }

        }
        elseif(is_array($arr[$i])){     
                MaxArray($arr[$i]);
            }
        }
    return $maxValue;   
}

Upvotes: 1

Views: 2163

Answers (2)

salathe
salathe

Reputation: 51950

A handy function for walking over nested arrays is array_walk_recursive(). It means that you don't have to worry about the handling the recursion yourself and can get on with the task at hand, in this case finding the maximum value.

function MaxArray($arr) {
    $max = FALSE;
    array_walk_recursive($arr, function ($current) use (&$max) {
        if ($max === FALSE) {
            $max = $current;
        } else {
            $max = max($current, $max);
        }
    });
    return $max;
}

Upvotes: 4

Levi Morrison
Levi Morrison

Reputation: 19552

Taken from PHP manual but authored by me:

/**
 * @param array $array
 *
 * @return int|null Returns the largest value of the array. Returns NULL if no 
 *     integers are found.
 */
function array_max_recursive(array $array) {
    $max = NULL;
    $stack = array($array);

    do {
        $current = array_pop($stack );
        foreach ($current as $value) {
            if (is_array($value)) {
                $stack[] = $value;
            } elseif (filter_var($value, FILTER_VALIDATE_INT) !== FALSE) {
                // max(NULL, 0) returns NULL, so cast it
                $max = (int) max($max, $value);
            }
        }

    } while (!empty($stack));

    return $max;
}

  • This function is not actually recursive, but fulfills the requirement that it works on sub-arrays. I enjoy doing things without the runtime stack from time to time.
  • It returns something of type int, never a string representation of an int. The exception is when you provide an array that does not contain any integers. It will then return NULL.
  • It ignores non-array, non-int values.

Upvotes: 5

Related Questions