PHP second highest value in array

Share Button

Find the 2nd largest element in an array

I have been asked many time in interviews that how to find a second height value in a array in PHP. First and easiest way is to use PHP inbuilt sort functions, here is the example

// for associative array
$array = array(
    "chocolate" => "20",
    "vanilla" => "14",
    "strawberry" => "18",
    "raspberry" => "19",
    "bluebery" => "29"
);
arsort($array);
$keys = array_keys($array);

echo $keys[1]; // chocolate
echo $array[$keys[1]]; // 20

// for array
$array = array(20, 14, 18, 19, 29);
arsort($array);

echo $array[1]; // 20

If you want a more efficient way, you can also do it manually, by keeping track of both the highest and second-highest items at the same time:

function secondMax($arr) {
$max = $second = 0;
$maxKey = $secondKey = null;

foreach($arr as $key => $value) {
    if($value > $max) {
        $second = $max;
        $secondKey = $maxKey;
        $max = $value;
        $maxKey = $key;
    } 
    elseif($value > $second) {
        $second = $value;
        $secondKey = $key;
    }
}

return array($secondKey, $second);
}

Usage:

$second = secondMax($array);
echo "{$second[0]} => {$second[1]}"; // chocolate > 20
//for array
function secondMax($arr) {
$max = $second = 0;

foreach($arr as $key => $value) {
    if($value > $max) {
        $second = $max;
        $max = $value;
    } 
    elseif($value > $second) {
        $second = $value;
    }
}

return array($second);
}

Usage:

$second = secondMax($array);
echo "{$second[0]}"; // 20
Share Button