Tuesday, 6 October 2015

GENERATE UNIQUE RANDOM NUMBERS WITHIN A RANGE USING PHP FUNCTION

The previous lesson of PHP Lessons Series was about comparison of associative arrays in PHP and in this lesson I have shared a PHP function to generate unique random numbers within a range using a PHP function. 

Unique Random Numbers in PHP

The PHP script given below generates unique random numbers between an upper and lower limit specified. Just change the values of the variables given below to meet your requirements: 


$numberOfNums = 10;   // Number of unique numbers to generate
$lowerLimit = 3;      // Lower Limit of unique numbers
$upperLimit = 60;     // Upper Limit of unique numbers


<?php
$numberOfNums = 10;
$lowerLimit = 3;
$upperLimit = 60;

$a = random_numbers($numberOfNums, $lowerLimit, $upperLimit);

$commaseparatedNums = $a;
echo 'Comma Separated: '.$a.'<br />';
$arrayNums = explode(',',$a);
echo '<pre>';
print_r($arrayNums);

function random_numbers($a, $b, $c){

    $n = array();
    for($i=0;$i<$a;$i++){
  $already = 0;
        do
        {
   $num = rand($b,$c);
   if($i != 0)
   {
    if (in_array($num,$n))
                {
                    $already = 1;
                                
    }
                else
                {
                    $already = 0;
     $n[$i] = $num;
     $single = $single.','.$n[$i];
                }
        
   }else if($i == 0){
    $n[$i] = $num;
    $single = $n[$i];
    $already = 0;
            }
        }
        while ($already != 0);
    }

    return $single;
}
?>

0 comments:

Post a Comment