Position of Max value in Array PHP
Hey guys, so I have two arrays
$names = array('jimmy', 'johnny', 'sarah');
$ages= array('1开发者_Python百科6', '18', '12');
I am trying to find the biggest/maximum value in ages, get that elements position and use said position to get the corresponding name. How would I achieve this?
Is there a better way to achieve the corresponding name, perhaps bundling all in one?
Thanks
This should get the key for you:
$names = array('jimmy', 'johnny', 'sarah');
$ages= array('16', '18', '12');
$oldest = array_search(max($ages), $ages);
echo $names[$oldest];
You should note though, that if two persons would have the same age, the first of these two persons would be the one returned.
if you need to find all the oldest you should use array_keys()
instead of array_search()
like this:
$names = array('jimmy', 'johnny', 'sarah', 'kristine');
$ages = array('16', '18', '12', '18');
$oldestPersons = array_keys($ages, max($ages));
foreach($oldestPersons as $key) {
echo $names[$key].'<br />';
}
$oldest_key = 0;
$age_var = 0;
foreach ($ages as $key => $age) {
if ($age > $age_var) {
$age_var = $age;
$oldest_key = $key;
}
}
echo "Oldest person is: {$names[$oldest_key]} ($age_var)";
Just for fun, here's another solution:
$names = array('jimmy', 'johnny', 'sarah');
$ages= array('16', '18', '12');
$people = array_combine($ages, $names);
ksort($people);
echo 'Oldest person is: '.end($people);
See it in action.
Note: If many people have the same age, the one appearing last in the input arrays gets picked. This is a result of the behavior of array_combine
.
精彩评论