PHP get min and max values from random numbers

I need to find the Minimum and Maximum number that was randomly generated using the code below. Any tips please on what function to use.

<?php


for ($i=0;$i<20;$i++) {

    $currentRandomNumber = rand(1,50);

    echo $currentRandomNumber . ' ';

}

?>

Use MIN and MAX functions. Store in array! Something like this:

<?php

$nums = array();
for ($i=0;$i<20;$i++) {
$currentRandomNumber[ $i ] = rand(1,50);
echo $currentRandomNumber[ $i ] . ’ ';
}
echo "LOWEST: " . min($nums) . “< br>”;
echo "HIGHTEST: " . max($nums);

?>

1 Like

If you don’t want to store all the numbers, you could do this:

<?php

$lowestNum = null;
$highestNum = null;

for ($i=0; $i<20; $i++) {
    $currentRandomNumber = rand(1,50);

    if (is_null($lowestNum) || $currentRandomNumber < $lowestNum) {
        $lowestNum = $currentRandomNumber;
    }

    if (is_null($highestNum) || $currentRandomNumber > $highestNum) {
        $highestNum = $currentRandomNumber;
    }
}

echo 'Lowest number was ', $lowestNum, PHP_EOL;
echo 'Highest number was ', $highestNum, PHP_EOL;

Every time you create a number, you check it against the previous highest number. If the number is higher, or you haven’t looked at any numbers yet, then the current number is your new best match. You do the same for the lowest number.

Sponsor our Newsletter | Privacy Policy | Terms of Service