Here's a nifty function that comes handy every now and then. It generates X number of random numbers, ranging from A to B, but with no duplicates. PHP's rand() produces more duplicates than anything 
CODE:
// php
// $num = number of 'numbers' to generate
// $start = start of range
// $end = end of range
function get_rand($num, $start, $end) {
$rand = array();
$rand_temp = array();
while(count($rand) < $num) {
$temp = rand($start, $end);
if(!isset($rand_temp[$temp])) {
$rand_temp[$temp] = true;
$rand[] = $temp;
}
}
return $rand;
}
// php
// $num = number of 'numbers' to generate
// $start = start of range
// $end = end of range
function get_rand($num, $start, $end) {
$rand = array();
$rand_temp = array();
while(count($rand) < $num) {
$temp = rand($start, $end);
if(!isset($rand_temp[$temp])) {
$rand_temp[$temp] = true;
$rand[] = $temp;
}
}
return $rand;
}

on March 22, 2008, 10:42 pm
( Reply to this comment )