note 33363 added to function.array-rand

From: Date: Tue, 24 Jun 2003 04:06:42 +0000
Subject: note 33363 added to function.array-rand
Groups: php.notes 
Request: Send a blank email to php-notes+get-50908@lists.php.net to get a copy of this message
It is correct that using array_rand() with num_req=1 will return an integer and not an array, but why get so complicated with getting just the one value. The K.I.S.S. method would suggest to do it this way: <? srand((double)microtime() * 10000000); $originalArray = array("red", "blue", "green", "brown", "cyan", "magenta", "purle", "cheezy"); $pickOne = array_rand($originalArray, 1); $aRandomSelection = $originalArray[$pickOne ]; echo "$aRandomSelection was the random selection made"; ?> You only need to use the foreach if the num_req >=2. In those cases the array_rand() function will return an array of random elements which are a subset of the original array. When num_req = 1, the array_rand() function returns an integer that signifies a randomly picked key of the original array. Hope this clarifies things ... it works for me. ---- Manual Page -- http://www.php.net/manual/en/function.array-rand.php Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+33363 Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+33363&report=yes Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+33363&report=yes

« previous php.notes (#50908) next »