Get the maximum value from an element in a multidimensional array? [duplicate]

In PHP 5.2 the only way to do this is to loop through the array.

$max = null;
foreach ($arr as $item) {
  $max = $max === null ? $item->dnum : max($max, $item->dnum);
}

Note: I’ve seeded the result with 0 because if all the dnum values are negative then the now accepted solution will produce an incorrect result. You need to seed the max with something sensible.

Alternatively you could use array_reduce():

$max = array_reduce($arr, 'max_dnum', -9999999);

function max_denum($v, $w) {
  return max($v, $w->dnum);
}

In PHP 5.3+ you can use an anonymous function:

$max = array_reduce($arr, function($v, $w) {
  return max($v, $w->dnum);
}, -9999999);

You can use array_map() too:

function get_dnum($a) {
  return $a->dnum;
}

$max = max(array_map('get_dnum', $arr));

Leave a Comment