Using PHP shuffle() to Randomly Rearrange Array Elements
This article explains PHP's shuffle() function, detailing its syntax, behavior of modifying the original array, return value, usage with indexed and associative arrays, and provides multiple code examples illustrating how to randomize array elements.
In PHP programming, the shuffle() function is used to randomize the order of elements in an array.
The function signature is:
shuffle(array &$array) : boolIt accepts an array by reference, shuffles its elements in place, and returns a boolean indicating success.
Example with an indexed array:
// Declare and initialize an array
$myArray = array("Apple", "Banana", "Cherry", "Durian");
// Print original array
echo "Original array:";
print_r($myArray);
// Shuffle the array
shuffle($myArray);
// Print shuffled array
echo "Shuffled array:";
print_r($myArray);The output shows the original order followed by a randomly reordered array.
The function also returns true on success, which can be used for conditional logic.
Note that shuffle() works only with indexed arrays; when applied to an associative array, it reindexes the keys to consecutive numbers. Example:
// Declare and initialize an associative array
$myArray = array("a" => "Apple", "b" => "Banana", "c" => "Cherry");
// Print original array
echo "Original array:";
print_r($myArray);
// Shuffle the array
shuffle($myArray);
// Print shuffled array
echo "Shuffled array:";
print_r($myArray);After shuffling, the keys are reset to 0, 1, 2, demonstrating the reindexing behavior.
Overall, shuffle() is a practical PHP function for randomizing array elements, and the provided examples help developers understand its usage.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.