Приглашаем посетить
Биология (bio.niv.ru)

Getting Random Elements Out of Arrays

Previous
Table of Contents
Next

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.

Getting Random Elements Out of Arrays


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.



Previous
Table of Contents
Next