How to Shuffle an Array in PHP

Updated: January 10, 2024 By: Guest Contributor Post a comment

Overview

Shuffling an array is a common task in programming when you need to randomize the order of elements. PHP provides a built-in function to shuffle arrays easily and effectively. This guide covers different ways to shuffle an array using PHP, with examples ranging from basic to advanced usage.

Introduction to array_shuffle()

PHP has a built-in function shuffle() which takes an array as an argument and returns the same array with its order randomized. This is the simplest and most straightforward method to shuffle an array in PHP.

Here is a basic example:

$array = range(1, 10);
echo 'Original array: ' . implode(', ', $array) . "\n";

shuffle($array);
echo 'Shuffled array: ' . implode(', ', $array);

Output:

Original array: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 

Shuffled array: 7, 3, 10, 2, 6, 1, 8, 4, 9, 5

Shuffling Associative Arrays

Since shuffle() re-indexes the keys of the array, it’s not suitable for associative arrays where key-value associations must be preserved. Instead, we can use a combination of PHP functions to achieve this.

Example:

$assoc_array = array("a"=>"apple", "b"=>"banana", "c"=>"cherry");
$keys = array_keys($assoc_array);

shuffle($keys);

$result = array();
foreach ($keys as $key) {
    $result[$key] = $assoc_array[$key];
}

echo 'Shuffled associative array: ';
print_r($result);

Output:

 Shuffled associative array: Array ( [c] => cherry [b] => banana [a] => apple )

Using array_rand()

The array_rand() function is another way to shuffle an array by selecting one or more random keys from the array. This method is particularly useful when you only need a subset of the shuffled array.

Example of selecting three random elements:

$numbers = range(1, 5);
$keys = array_rand($numbers, 3);

$random_elements = array_intersect_key($numbers, array_flip($keys));
print_r($random_elements);

Output:

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

Custom Shuffle Algorithm

If you require more control over the shuffling process or want to implement your own algorithm (such as the Fisher-Yates shuffle), PHP’s functions offer the flexibility to do so.

Example of the Fisher-Yates shuffle:

function fisherYatesShuffle(&$items) {
    for ($i = count($items) - 1; $i > 0; $i--) {
        $j = random_int(0, $i);
        $temp = $items[$i];
        $items[$i] = $items[$j];
        $items[$j] = $temp;
    }
}

$array = range(1, 10);
fisherYatesShuffle($array);
print_r($array);

Output will be a randomly ordered array each time the script runs.

Sorting with Callbacks

Another advanced method involves using usort() with a custom comparison function that returns random order values to shuffle an array.

Example:

function randomCompare($a, $b) {
    return rand(0, 1) ? -1 : 1;
}

$array = range(1, 10);
usort($array, "randomCompare");
print_r($array);

The execution output will vary as the comparison function returns random results, resulting in a shuffled array.

Conclusion

Shuffling arrays in PHP can be done using a variety of methods depending on the specific requirements of the task at hand. Whether it’s using the simple shuffle() for indexed arrays or more sophisticated techniques for associative arrays, PHP’s versatility allows developers to efficiently introduce randomness into their data structures.