How to find the second biggest number in a set of random numbers in PHP

1 Answer

0 votes
function findSecondMax($total, $rndmax) {
    $numbers = [];

    for ($i = 0; $i < $total; $i++) {
        $n = rand(1, $rndmax);
        $numbers[] = $n;
        echo $n . PHP_EOL;
    }

    $uniqueNumbers = array_unique($numbers);
    rsort($uniqueNumbers);

    return count($uniqueNumbers) > 1 ? $uniqueNumbers[1] : null;
}

$secondMax = findSecondMax(10, 100);

if ($secondMax !== null) {
    echo "The second biggest number is: $secondMax" . PHP_EOL;
} else {
    echo "Not enough unique numbers to determine a second maximum." . PHP_EOL;
}



/*
run:

30
62
4
4
24
47
39
73
37
29
The second biggest number is: 62

*/

 



answered Oct 4, 2025 by avibootz
...