Simple:
//setup
class user{
public $number;
}
//init
$user1 = new user();
$user1->number = 3;
$user2 = new user();
$user2->number = 8;
$user3 = new user();
$user3->number = 5;
$a = [$user1, $user2, $user3];
$max = 0;
//execute
$o = array_reduce($a,function($c,$v){return$c->number<$v->number?$v:$c;},new user);
//output
print_r($o);
Output:
user Object
(
[number:protected] => 8
)
Sandbox
Note only this part is the actual function:
$o = array_reduce($a,function($c,$v){return$c->number<$v->number?$v:$c;},new user);
The rest is just setup, but I think it is better to post the full working example and then explain off of that.
Here is the code uncompressed:
$o = array_reduce(
$a,
function($c,$v){
return $c->number < $v->number ? $v : $c;
},
new user //init a new user object for $c's initial value, number = null
);
It's pretty strait forward, we do array reduce. If $v has a value greater then the carried item $c, we set the carried item to $v. If not we just return the carried item. And in the end, we are left with one item that has the max value.
If you wanted a bit more assurance and robustness, you can type hint the arguments of the callback to only accept user type objects:
$o = array_reduce(
$a,
function(user $c, user $v){
return $c->number < $v->number ? $v : $c;
},
new user //init a new user object for $c's initial value, number = null
);
This binds us to the user classes API or interface. Which insures that only user objects are accepted, so we can reduce our error checks as we know what type of object it is, and what methods it has...
But, pretty much no matter what you do you have to iterate over the entire array at least one time to "discover" all the values.