0

I've got an array of input data and I need to find the max and min values. The POST array could look like any of the following, depending on the options the user selected:

[a] => Array
(
    [0] => 2
)

[a] => Array
    (
        [0] => 2
        [1] => 4
        [2] => 7
    )
[a] => Array
    (
        [0] => 2
        [1] => 4
        [2] => Array
            (
                [0] => 7
            )

    )

I had it working by sorting the array and grab the min and max values when 'a' was always a single-dimensional array, but since we've added the option for it to be multidimensional I'm stuck.

Cœur
  • 37,241
  • 25
  • 195
  • 267
gandalf007
  • 87
  • 7
  • This http://stackoverflow.com/questions/4497810/min-and-max-in-multidimensional-array – IsisCode Jan 31 '12 at 00:15
  • Flatten the array first http://stackoverflow.com/questions/7011451/transaprently-flatten-an-array and then apply the `max()` function. – mario Jan 31 '12 at 00:17
  • I thought about flattening it but didn't want to risk overwriting existing keys. Maybe I was going about it wrong – gandalf007 Jan 31 '12 at 00:22

1 Answers1

2

I would use an Iterator: http://php.net/spl.iterators.php

function array_max($arr) {
  $max = null;

  foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($arr)) as $value) {
    if ($max === null || $value > $max) {
      $max = $value;
    }
  }
  return $max;
}

I think you can figure out how to do array_min() on your own.

nachito
  • 6,975
  • 2
  • 25
  • 44