note 77065 deleted from function.rand by felipe

From: Date: Sun, 30 Dec 2007 18:46:38 +0000
Subject: note 77065 deleted from function.rand by felipe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-134459@lists.php.net to get a copy of this message
Note Submitter: alishahnovin at hotmail dot com ---- Quick function that returns an array of unequal random numbers. Works well if you need to assign random values, but want them to all be unique. <?php 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; } } ?> So rather than: <?php $var1 = rand(0,10); $var2 = rand(0,10); ?> Which could potentially give you two of the same values, you can use: <?php $nums = randiff(0,10,2); $var1 = $nums[0]; $var2 = $nums[1]; ?>

« previous php.notes (#134459) next »