Getting Random Elements Out of Arrays


 array_rand($numbers, 6) 


With array_rand(), one or more random elements out of an array are determined by random. This can, for instance, be used to draw some lucky numbers. For instance, the German lottery draws six numbers out of 49. The preceding code implements this drawing using PHP and array_rand(); see Figure 2.7 for its output. The first parameter for this function is the array; the second (optional) one is the number of elements to be returned.

Picking Random Elements Out of an Array (array_rand.php)
 <?php   for ($i = 1; $i <= 49; $i++) {     $numbers[] = $i;   }   echo implode(' ', array_rand($numbers, 6)); ?> 

Figure 2.7. Lucky numbers with PHP.


NOTE

If you do not want to pick random elements but want to randomize the order of elements in the array (for example, when shuffling a deck of cards), use the shuffle() function.





PHP Phrasebook
PHP Phrasebook
ISBN: 0672328178
EAN: 2147483647
Year: 2005
Pages: 193

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net