How can I find the max attribute in an array of objects?

try this:

$point1 = new stdClass;
$point1->value = 0.2;
$point1->name = 'Bob';

$point2 = new stdClass;
$point2->value = 1.2;
$point2->name = 'Dave';

$point3 = new stdClass;
$point3->value = 0.8;
$point3->name = 'Steve';

$data_points = [$point1, $point2, $point3];

function max_attribute_in_array($data_points, $value='value'){
    $max=0;
    foreach($data_points as $point){
        if($max < (float)$point->{$value}){
            $max = $point->{$value};
        }
    }
    return $max;
}
$max = max_attribute_in_array($data_points);
var_dump($max);

response:

float 1.2

All examples assume that $prop is the name of an object property like value in your example:

function max_attribute_in_array($array, $prop) {
    return max(array_map(function($o) use($prop) {
                            return $o->$prop;
                         },
                         $array));
}
  • array_map takes each array element and returns the property of the object into a new array
  • Then just return the result of max on that array

For fun, here you can pass in max or min or whatever operates on an array as the third parameter:

function calc_attribute_in_array($array, $prop, $func) {
    $result = array_map(function($o) use($prop) {
                            return $o->$prop;
                        },
                        $array);

    if(function_exists($func)) {
        return $func($result);
    }
    return false;
}

$max = calc_attribute_in_array($data_points, 'value', 'max');
$min = calc_attribute_in_array($data_points, 'value', 'min');

If using PHP >= 7 then array_column works on objects:

function max_attribute_in_array($array, $prop) {
    return max(array_column($array, $prop));
}

Here is Mark Baker's array_reduce from the comments:

$result = array_reduce(function($carry, $o) use($prop) {
                           $carry = max($carry, $o->$prop);
                           return $carry;
                       }, $array, -PHP_INT_MAX);

Tags:

Php

Arrays

Object