Search code examples
phparraysmultidimensional-arraymaxarray-column

Get max value from each column of a 2-dimensional array


I have an array within an array, for example:

[ 
    [0, 20, 5], 
    [5, 0, 15], 
    [5, 10, 0]
]

I need to get the max number in each column.

  • The max of [0 , 5 , 5] is 5, so that goes into the result array.
  • The max of [20, 0, 10] is 20, so that goes into the result array.
  • The max of [5, 15, 0] is 15, so that goes into the result array.

The final result array must contain [5, 20, 15].


Solution

  • First, the array has to be transposed (flip the rows and columns):

    function array_transpose($arr) {
       $map_args = array_merge(array(NULL), $arr);
       return call_user_func_array('array_map', $map_args);
    }
    

    (taken from Is there better way to transpose a PHP 2D array? - read that question for an explanation of how it works)

    Then, you can map the max function on the new array:

    $maxes = array_map('max', array_transpose($arr));
    

    Example: http://codepad.org/3gPExrhO

    Output [I think this is what you meant instead of (5, 15, 20) because you said index 1 should be max of (20, 0, 10)]:

    Array
    (
        [0] => 5
        [1] => 20
        [2] => 15
    )