A php function to return random values

I was looking for a method in php that would return unequal numbers using the rand() function. I found an answer on php.net and all credit goes to alishahnovin at hotmail dot com. The method is as follows:

function randiff($min, $max, $num) {
    if ($min<$max && $max-$min+1 >= $num && $num>0) {
        $random_nums = array();
        $i=0;
        while($i<$num) {
            $rand_num = rand($min, $max);
            if (!in_array($rand_num, $random_nums)) {
                $random_nums[] = $rand_num;
                $i++;
            }
        }
        return $random_nums;
    } else {
        return false;
    }
}

Usage:

$nums = randiff(0,10,2);
$var1 = $nums[0];
$var2 = $nums[1];
This entry was posted in Web and tagged , , . Bookmark the permalink.

One Response to A php function to return random values

  1. Emilia says:

    cholera..Piotrek..ja sie tu nie moge polapac..!!!!!!!!!! i dla mnie zamale wszystko… hehehe !:p

    buziaki ze Szczecina!

Leave a Reply

Your email address will not be published. Required fields are marked *