note 54585 deleted from function.rand by felipe

[email protected]
Newsgroups php.notes
Message-ID <[email protected]>
Note Submitter: mark at mmpro dot de 

----

I needed to generate a random array of different(!) numbers, i.e. no number in the array should be duplicated. I used the nice functions from phpdeveloper AT o2 DOT pl but it didn't work as I thought. 

So I varied it a little bit and here you are:

function RandomArray($min,$max,$num) {

$ret = array();

// as long as the array contains $num numbers loop
while (count($ret) <$num) {
	do {
		$a = rand($min,$max);
		//
		#echo $a."<br />";
	}
	// check if $a is already in the array $ret 
	// if so, make another random number
	while (in_array($a,$ret));
	// add the new random number to the end of the array
	$ret[] = $a;
}
return($ret);

}

// generate an array of 3 numbers between 10 and 19
$ret = randomArray(10,19,3)

echo $ret[0]."-".$ret[1]."-".$ret[2];
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.