note 77065 added to function.rand

From: Date: Mon, 13 Aug 2007 17:39:16 +0000
Subject: note 77065 added to function.rand
Groups: php.notes 
Request: Send a blank email to php-notes+get-129450@lists.php.net to get a copy of this message
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]; ?> ---- Server IP: 66.207.199.35 Probable Submitter: 204.244.149.125 ---- Manual Page -- http://www.php.net/manual/en/function.rand.php Edit -- https://master.php.net/note/edit/77065 Del: integrated -- https://master.php.net/note/delete/77065/integrated Del: useless -- https://master.php.net/note/delete/77065/useless Del: bad code -- https://master.php.net/note/delete/77065/bad+code Del: spam -- https://master.php.net/note/delete/77065/spam Del: non-english -- https://master.php.net/note/delete/77065/non-english Del: in docs -- https://master.php.net/note/delete/77065/in+docs Del: other reasons-- https://master.php.net/note/delete/77065 Reject -- https://master.php.net/note/reject/77065 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#129450) next »