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

Solution 1:

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));

Solution 2:

$max = 0;
foreach($array as $obj)
{
    if($obj->dnum > $max)
    {
        $max = $obj->dnum;
    }
}

That function would work correctly if your highest number is not negative (negatives, empty arrays, and 0s will return the max as 0).

Because you are using an object, which can have custom properties/structures, I don't believe there are really any 'predefined' functions you can use to get it. Might as well just use a foreach loop.

You really can't get away from a foreach loop, as even internal functions use a foreach loop, it is just behind the scenes.

Another solution is

$numbers = array();
foreach($array as $obj)
{
    $numbers[] = $obj->dnum;
}
$max = max($numbers);