Using PHP shuffle() to Randomly Rearrange Array Elements
This article explains PHP's shuffle() function, its syntax, behavior, return value, and demonstrates how it randomizes both indexed and associative arrays with code examples, highlighting that it modifies the original array and reindexes non‑sequential keys.
In PHP programming, the shuffle() function is a useful built‑in utility that randomizes the order of elements in an array. It operates directly on the supplied array, altering its order in place, and returns a boolean indicating success.
The function signature is:
<code>shuffle(array &$array) : bool</code>The single parameter $array must be an array; after calling shuffle() the original array is shuffled, and the function does not create a new array.
Example with an indexed array:
<code>// Declare and initialize an indexed array
$myArray = array("Apple", "Banana", "Cherry", "Durian");
// Print the original array
echo "Original array: ";
print_r($myArray);
// Shuffle the array
shuffle($myArray);
// Print the shuffled array
echo "Shuffled array: ";
print_r($myArray);
</code>Running the code produces output similar to:
<code>Original array: Array
(
[0] => Apple
[1] => Banana
[2] => Cherry
[3] => Durian
)
Shuffled array: Array
(
[0] => Durian
[1] => Apple
[2] => Banana
[3] => Cherry
)
</code>The function also returns a boolean value that can be used to verify whether the shuffle succeeded, although the example above does not check it.
Note that shuffle() works only with indexed arrays (keys starting at 0 and sequential). When applied to an associative (non‑indexed) array, the keys are re‑indexed to a continuous numeric sequence.
Example with a non‑indexed array:
<code>// Declare and initialize a non‑indexed array
$myArray = array("a" => "Apple", "b" => "Banana", "c" => "Cherry");
// Print the original array
echo "Original array: ";
print_r($myArray);
// Shuffle the array
shuffle($myArray);
// Print the shuffled array
echo "Shuffled array: ";
print_r($myArray);
</code>The resulting output shows the keys have been re‑indexed:
<code>Original array: Array
(
[a] => Apple
[b] => Banana
[c] => Cherry
)
Shuffled array: Array
(
[0] => Apple
[1] => Banana
[2] => Cherry
)
</code>In summary, shuffle() is a practical PHP function for randomizing array elements, modifying the original array, and re‑indexing non‑sequential keys when necessary.
Recommended PHP learning resources:
Vue3+Laravel8+Uniapp Beginner to Project Development Tutorial
Vue3+TP6+API Social E‑commerce System Development Course
Swoole From Beginner to Master Course
Workerman+TP6 Real‑time Chat System Limited‑time Offer
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.