开发者

Position of Max value in Array PHP

开发者 https://www.devze.com 2023-03-04 13:30 出处:网络
Hey guys, so I have two arrays $names = array(\'jimmy\', \'johnny\', \'sarah\'); $ages= array(\'1开发者_Python百科6\', \'18\', \'12\');

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号