The shuffle Function

The shuffle function shuffles an array so that its elements are in random order. The function modifies the array itself: this means the result of the function does not need to be assigned anywhere - the changes will occur to the array itself.

Syntax

phpshuffle(array &$array): bool

Example

Let's shuffle array elements in random order:

php<?php
  $arr = [1, 2, 3, 4, 5];
  
  shuffle($arr);
  var_dump($arr);
?>

Example . Usage

Let's fill an array with numbers from 1 to 10 so that they are in random order and do not repeat. To do this, we will generate an array with numbers from 1 to 10 using range and shuffle it using shuffle:

php<?php
  $arr = range(1, 10);
  
  shuffle($arr);
  var_dump($arr);
?>

Example . Usage

Let's create a ul list, filled with random numbers from 1 to 10:

php<?php
  $arr = range(1, 10);
  shuffle($arr);
  
  echo '<ul>';
  foreach ($arr as $elem) {
    echo '<li>' . $elem . '</li>';
  }
  echo '</ul>';
?>

See Also

  • the str_shuffle function,
    which shuffles string characters in random order
  • the array_rand function,
    which selects random values from an array
  • the mt_rand function,
    which generates random numbers