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, $po
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);