Is there a PHP v5.5 equilavent to max for lodash/underscore?
Basically I would like to be able to do something similar to this:
$characters = [
{ 'name': 'barney', 'age': 36 },
{ 'name': 'fred', 'age': 40 }
];
max($characters, 'age');
// → { 'name': 'fred', 'age': 40 };
There is a port of Underscore called Underscore.php which provides the max function (as well as many other Underscore functions).
From its documentation:
$stooges = array(
array('name'=>'moe', 'age'=>40),
array('name'=>'larry', 'age'=>50),
array('name'=>'curly', 'age'=>60)
);
__::max($stooges, function($stooge) { return $stooge['age']; });
// array('name'=>'curly', 'age'=>60)
Might be a slicker way, but here's one:
$result = $characters[array_search(max($a=array_column($characters, 'age')),$a)];
print_r($result);
(
[name] => fred
[age] => 40
)
Using a sort:
array_multisort(array_column($characters, 'age'), SORT_DESC, $characters);
print_r($characters[0]);
NOTE: array_column
requires PHP >= 5.5.0
Easiest way would be to iterate over them and just look, where the biggest value is:
// All examples php 5.4+
$characters = [
[ 'name'=> 'barney', 'age'=> 36 ],
[ 'name'=> 'fred', 'age'=> 26 ],
[ 'name'=> 'fred4', 'age'=> 23 ],
[ 'name'=> 'fred5', 'age'=> 82 ],
[ 'name'=> 'fred6', 'age'=> 24 ],
];
if(!isset($characters[0]['age']) { die('wrong array structure'); }
$maxLocation = 0;
foreach($characters as $position => $value) {
if($value['age'] > $characters[$maxLocation]['age']) {
$maxLocation = $position;
}
}
var_dump($characters[$maxLocation]);
Ordering them might be an overkill, however, if you need to act on them later:
usort($characters, function($a, $b) {
if($a['age'] === $b['age']) {
return 0;
}
return $a['age'] < $b['age'] ? 1 : -1;
});
var_dump($characters[0]);
Using PHP 5.5's array_column() to tweak the structure of the original array slightly:
$characters = [
[ 'name' => 'barney', 'age' => 36 ],
[ 'name' => 'fred', 'age' => 40 ],
[ 'name' => 'wilma', 'age' => 35 ],
[ 'name' => 'betty', 'age' => 34 ],
];
arsort($simple = array_column($characters, 'age', 'name'));
$max = array_slice($simple, 0, 1);
var_dump($max);
After reading all the solutions, I guess the answer to this problem is:
No, there isnt any equivalent to "max" in PHP
But I will upvote every answer that gave me an alternative method to do it. Thanks guys.