Home > Articles > Programming > PHP

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Getting Random Elements Out of Arrays

array_rand($numbers, 6)
<?php
  for ($i = 1; $i <= 49; $i++) {
    $numbers[] = $i;
  }
  // we could use range() instead, too

  echo implode(' ', array_rand($numbers, 6));
?>

Picking Random Elements Out of an Array (array_rand.php)

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 6 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.

Figure 2.7

Figure 2.7. Lucky numbers with PHP

  • + Share This
  • 🔖 Save To Your Account