Array Functions
Advertisements

PHP shuffle() Function

Topic: PHP Array ReferencePrev|Next

Description

The shuffle() function shuffles an array (i.e. randomizes the order of the array elements).

The following table summarizes the technical details of this function.

Return Value: Returns TRUE on success or FALSE on failure.
Changelog: Since PHP 7.1.0, the internal randomization algorithm has been changed to use the Mersenne Twister random number generator instead of the libc rand function.
Version: PHP 4+

Syntax

The basic syntax of the shuffle() function is given with:

shuffle(array);

The following example shows the shuffle() function in action.

<?php
// Sample array
$colors = array("red", "green", "blue", "orange", "yellow", "black");

// Shuffling the indexed array colors
shuffle($colors);
print_r($colors);
?>

Note: The shuffle() function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys.


Parameters

The shuffle() function accepts the following parameters.

Parameter Description
array Required. Specifies the array to work on.

More Examples

Here're some more examples showing how shuffle() function actually works:

You can also shuffle an associative array, but the original keys will be removed, as stated above.

<?php
// Sample array
$alphabets = array("a"=>"apple", "b"=>"ball", "c"=>"cat", "d"=>"dog");

// Sorting the associative array alphabets
shuffle($alphabets);
print_r($alphabets);
?>
Advertisements
Bootstrap UI Design Templates