note 33363 deleted from function.array-rand by cmb

From: Date: Sun, 18 Oct 2020 11:00:57 +0000
Subject: note 33363 deleted from function.array-rand by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-215607@lists.php.net to get a copy of this message
Note Submitter: asarnoNOSPAM@interbaun DOT com ---- 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.

« previous php.notes (#215607) next »