PHP shuffle() Function: Randomly Reordering Arrays with Detailed Examples
This article explains the PHP shuffle() function, its syntax, parameters, return values, and demonstrates three practical examples showing how to randomize indexed and associative arrays, highlighting the effect on array keys and values after shuffling.
The shuffle() function in PHP randomly rearranges the order of elements in an array.
Syntax:
bool shuffle (array &$array)
It takes a single argument – the array to be shuffled – passed by reference, and returns TRUE on success or FALSE on failure.
Example 1 – Shuffling a numeric indexed array:
<?php $numbers = range(1, 20); shuffle($numbers); foreach ($numbers as $number) { echo "$number "; } ?>
This creates an array of numbers from 1 to 20, shuffles it, and prints the numbers in their new random order.
Example 2 – Shuffling a simple indexed array of strings:
<?php $my_array = array("red", "green", "blue", "yellow", "purple"); shuffle($my_array); print_r($my_array); ?>
After shuffling, the array retains numeric indexes (0, 1, 2, …) but the values appear in a random sequence.
Example 3 – Shuffling an associative array:
<?php $my_array = array( "a" => "red", "b" => "green", "c" => "blue", "d" => "yellow", "e" => "purple" ); shuffle($my_array); print_r($my_array); ?>
When an associative array is shuffled, its original keys are discarded and the result becomes a re‑indexed numeric array, with only the values shuffled.
These examples illustrate that shuffle() randomizes the order of elements, but for associative arrays the keys are lost, turning them into indexed arrays.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
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.