PHP shuffle Function
last modified March 13, 2025
The PHP shuffle
function randomizes the order of elements in
an array. It modifies the original array directly and returns true on success.
Basic Definition
The shuffle
function reorders array elements randomly. It uses
a pseudo-random number generator to create the new order. The function works
on both indexed and associative arrays.
Syntax: shuffle(array &$array): bool
. Note it takes the array by
reference and modifies it directly. Numeric keys are re-indexed starting from 0.
Basic shuffle Example
This demonstrates shuffling a simple indexed array of numbers.
<?php $numbers = [1, 2, 3, 4, 5]; shuffle($numbers); print_r($numbers);
Each run produces different output like [3, 1, 5, 2, 4]
. The
original array order is lost, and keys are re-indexed starting from 0.
Shuffling Associative Arrays
When shuffling associative arrays, string keys are lost and replaced with numeric indices.
<?php $colors = [ 'red' => '#FF0000', 'green' => '#00FF00', 'blue' => '#0000FF' ]; shuffle($colors); print_r($colors);
Output might be Array ( [0] => #00FF00 [1] => #0000FF [2] => #FF0000 )
.
The string keys are lost during shuffling, which is important to remember.
Preserving Keys While Shuffling
To shuffle while preserving keys, we can use array_keys
and
array_values
with some additional logic.
<?php function shuffle_assoc(array &$array): void { $keys = array_keys($array); shuffle($keys); $new = []; foreach ($keys as $key) { $new[$key] = $array[$key]; } $array = $new; } $data = ['a' => 1, 'b' => 2, 'c' => 3]; shuffle_assoc($data); print_r($data);
This custom function shuffles while keeping key-value pairs intact. Output
might be Array ( [b] => 2 [a] => 1 [c] => 3 )
with random order.
Shuffling Multidimensional Arrays
For multidimensional arrays, we need to decide whether to shuffle the outer array or inner arrays.
<?php $deck = [ ['suit' => 'hearts', 'value' => 'K'], ['suit' => 'diamonds', 'value' => 'A'], ['suit' => 'clubs', 'value' => 'Q'] ]; shuffle($deck); print_r($deck);
This shuffles the order of cards in the deck while keeping each card's structure intact. The inner arrays remain unchanged, just their order varies.
Creating a Random Sample
Combine shuffle
with array_slice
to get a random
sample from an array.
<?php $students = ['Alice', 'Bob', 'Charlie', 'David', 'Eve']; shuffle($students); $randomThree = array_slice($students, 0, 3); print_r($randomThree);
This selects 3 random students from the list. Each run produces different
results like ['David', 'Alice', 'Charlie']
.
Best Practices
- Backup Data: Make a copy if you need the original order.
- Associative Arrays: Be aware key-value pairs are lost.
- Randomness: For cryptography, use cryptographically secure functions.
- Performance: Shuffle is efficient even for large arrays.
Source
This tutorial covered the PHP shuffle
function with practical
examples showing its usage for array randomization scenarios.
Author
List all PHP Array Functions.