0

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].

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Kamal
  • 363
  • 8
  • 25

2 Answers2

4

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
)
Community
  • 1
  • 1
Tom Smilack
  • 2,057
  • 15
  • 20
0

Without the splat operator, array_map() with max() will return the max value for each row. ([20, 15, 10])

With the splat operator to transpose the data structure, the max value for each column is returned.

Code: (Demo)

$array = [ 
    [0, 20, 5], 
    [5, 0, 15], 
    [5, 10, 0]
];

var_export(
    array_map('max', ...$array)
);

Output:

array (
  0 => 5,
  1 => 20,
  2 => 15,
)
mickmackusa
  • 43,625
  • 12
  • 83
  • 136