I like the answer of @matteo-tassinari and @evilive much more and wanted to propose it myself. But since the question of efficency came up, here is a solution using only one loop and therefore has a linear time complexity:
<?php
$max = ~PHP_INT_MAX;
$result = [];
foreach($age as $key => $value) {
if($value > $max) {
$result = [ $key => $value ];
$max = $value;
}
if($value == $max) {
$result[$key] = $value;
}
}
var_dump($result);
Edit:
Regarding the discusson about peformance, I wrote a small benchmark script for three kinds of proposed solutions (loop, sort, filter):
<?php
$age = [];
for($i = 0; $i < 400000; $i++) {
$age['name_'.$i] = rand(0,100);
}
function loop($age) {
$max = 0;
$result = [];
foreach($age as $key => $value) {
if($value > $max) {
$result = [ $key => $value ];
$max = $value;
}
if($value == $max) {
$result[$key] = $value;
}
}
return $result;
}
function filter($ages) {
$max = max($ages);
$new = array_filter($ages, function ($age) use ($max) { return $age == $max; });
return $new;
}
$start = microtime(true);
loop($age);
echo "LOOP:\t" . (microtime(true) - $start.PHP_EOL);
$start = microtime(true);
arsort($age);
echo "SORT:\t" . (microtime(true) - $start.PHP_EOL);
$start = microtime(true);
filter($age);
echo "FILTER:\t" . (microtime(true) - $start.PHP_EOL);
Live Test
Please double-check if this is right, but my timings look something like this:
LOOP: 0.078601121902466
SORT: 0.30844783782959
FILTER: 0.18877291679382
array("Peter" => 35)
. Integers are faster than strings, use them where you can :) – Martijn 2 days ago