Randomize Array in PHP Using shuffle

This article explains how to randomize the order of elements within an array in place using PHP’s built-in shuffle() function. You will learn how the function works, see practical code examples of its implementation, and understand how it handles both indexed and associative arrays.

To randomize an array in place in PHP, you pass the array as an argument to the shuffle() function. Because the function accepts the array by reference, it modifies the original array directly and returns a boolean value (true on success or false on failure) rather than returning a new randomized array.

How to Shuffle an Indexed Array

Here is a straightforward example of using shuffle() on a standard indexed array:

<?php
$numbers = [1, 2, 3, 4, 5];

// Randomize the array in place
if (shuffle($numbers)) {
    print_r($numbers);
}
?>

Output: The output will be a randomized version of the original array, such as:

Array
(
    [0] => 3
    [1] => 5
    [2] => 1
    [3] => 2
    [4] => 4
)

Key Behavior: Key Resetting

It is important to note that shuffle() assigns new numeric keys to all elements in the array. If you use it on an associative array, any custom keys you have defined will be lost and replaced with zero-based sequential integers.

<?php
$colors = [
    'a' => 'red',
    'b' => 'blue',
    'c' => 'green'
];

shuffle($colors);
print_r($colors);
?>

Output:

Array
(
    [0] => blue
    [1] => red
    [2] => green
)

If you need to preserve the association between keys and values while randomizing, you should use alternative methods, such as utilizing asort() with a custom comparison function or extracting, shuffling, and combining the keys. However, for standard lists where keys do not matter, shuffle() is the most efficient and direct solution.