2

Hey guys, so I have two arrays

$names = array('jimmy', 'johnny', 'sarah');
$ages= array('16', '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

3 Answers 3

3

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 />';
}
Sign up to request clarification or add additional context in comments.

Comments

1
$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)";

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.