How can I find the maximum value for the objects in my array?
Say I have an array of objects like this:
$data_points = [$point1, $point2, $point3];
where
$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';
I would like to do something like this:
$max = max_attribute_in_array($data_points, 'value');
I know I can iterate over the array with a foreach but is there a more elegant method using built-in functions?
Maximum value of an attribute in an array of objects can be searched in two ways, one by traversing the array and the other method is by using the Math. max. apply() method.
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 arraymax on that arrayFor 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With