PHP shuffle()

MMOOAAZZ's avatar
Published Aug 8, 2023
Contribute to Docs

The shuffle() function randomizes the indexes of the elements in a given array.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours

Syntax

shuffle($array)

The shuffle() function has only one parameter:

  • $array: Specifies the array to randomize.

The shuffle() function returns an array with randomized elements.

Example

The following example uses the shuffle() function to randomize an array of numbers:

<?php
$numArray = array(1,2,3,4,5,6,7);
shuffle($numArray);
print_r($numArray);
?>

The example will result in an output similar to the following:

Array ( [0] => 2 [1] => 6 [2] => 3 [3] => 4 [4] => 1 [5] => 5 [6] => 7 )

Codebyte Example

This example is runnable and demonstrates a simple lottery randomizer which uses the shuffle() function:

Code
Output

All contributors

Contribute to Docs

Learn PHP on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours