note 73731 added to function.rand

From: Date: Thu, 08 Mar 2007 05:41:08 +0000
Subject: note 73731 added to function.rand
Groups: php.notes 
Request: Send a blank email to php-notes+get-124224@lists.php.net to get a copy of this message
#correction of my last post, wrong operator on ($keys < count($returnme)-1) , additional reset arg added for frequent use Trying to pick up random keys from an array but don't want any duplicates? try this <?php //returns an array of random keys between 2 numbers function &UniqueRands($min, $max, $keys, $reset=true){ static $returnme = array(); if($reset) $returnme = array(); //while is used to avoid recursive the whole function while(in_array($x = rand($min,$max),$returnme)); $returnme[] = $x; //$keys are the number of random integers in the array //must not be more than the sub of max - min if($keys > count($returnme) && count($returnme) < ($max-$min)) UniqueRands($min, $max, $keys,false); return $returnme; } //usage $rands = & UniqueRands(0, 100, 30); print_r($rands); //with an array $vararry = array('red', 'blue', 'green', 'yellow','black'); $rands = & UniqueRands(0, count($vararry)-1, 3); foreach($rands as $x) echo "$vararry[$x],"; ?> ---- Server IP: 69.147.83.197 Probable Submitter: 217.54.2.182 ---- Manual Page -- http://www.php.net/manual/en/function.rand.php Edit -- https://master.php.net/note/edit/73731 Del: integrated -- https://master.php.net/note/delete/73731/integrated Del: useless -- https://master.php.net/note/delete/73731/useless Del: bad code -- https://master.php.net/note/delete/73731/bad+code Del: spam -- https://master.php.net/note/delete/73731/spam Del: non-english -- https://master.php.net/note/delete/73731/non-english Del: in docs -- https://master.php.net/note/delete/73731/in+docs Del: other reasons-- https://master.php.net/note/delete/73731 Reject -- https://master.php.net/note/reject/73731 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#124224) next »