PHP provides the built-in ability to randomly sort, i.e. shuffle, an array of values in place. The PHP shuffle()
function takes a standard array of values and swaps each element randomly with another element in the array.
The shuffle terminology comes from what you would do if you needed to shuffle a deck of playing cards. The array could easily represent a pack of playing cards by having 52 cards stored in it, in a sorted fashion, e.g. Ace through King of Hearts, Ace through to King of Diamonds, Ace through to King of Clubs, and Ace through to King of Spades. The shuffle()
function would then randomly shuffle the deck of cards. It would then be a trivial matter to use the array_pop()
function to deal cards from the deck to each player in a game of Blackjack or Poker.
The original array is used to perform this swapping, so if you need to preserve the order of the values, you should duplicate the by using code similar to:
$new_array = $original_array;
before invoking the shuffle()
function.
Because the position of each element in a PHP array is based on a key, even if that key is treated like an index, using the shuffle()
function will assign new keys to each element in the array. Existing keys representing positions of elements in the PHP array are removed.
A successful shuffle()
operation will return Boolean TRUE
. If the shuffle()
function fails for any reason, e.g. the source PHP array is empty or a NULL
value is passed as the source array, the shuffle()
function returns a value of FALSE
.
shuffle()
Function Definitionbool shuffle(array &$source_array)
source_array |
Required |
The source array to be shuffled. |
Returns Boolean TRUE
on success, FALSE
on failure.
This example shows how to randomly shuffle elements in an array.
shuffle()
function to randomly sort the array.<?php
// allocate a small array of integers
$numbers = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// randomly shuffle the integers
shuffle($numbers);
// output each number in the now shuffled array
print_r($numbers);
?>
array(10) { [0]=> int(5) [1]=> int(6) [2]=> int(7) [3]=> int(4) [4]=> int(2) [5]=> int(1) [6]=> int(8) [7]=> int(9) [8]=> int(10) [9]=> int(3) }
As you can see the output of the program has randomly sorted the array of integers. Note that the array is shuffled in place, i.e. a new array is not created to perform the randomisation.
The ability to randomly sort an array of values with the shuffle()
function without having to write any additional code on your part is immensely useful for speed of development. Many languages do not provide this feature and surprisingly, just like the inverse of this function, the sort, it is functionality that is used over and over again in many applications.