Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

object

php

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?

like image 696
Pete Thorne Avatar asked Apr 13 '16 14:04

Pete Thorne


People also ask

How do you find the max value of an attribute in an array object?

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.


1 Answers

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);
like image 189
AbraCadaver Avatar answered Oct 05 '22 23:10

AbraCadaver