Shuffle an Array Without Using shuffle() in PHP

The shuffle() function in PHP randomizes the order of elements in an array. However, if you want to achieve the same without using built-in array functions, you can implement a manual random shuffling algorithm, such as the Fisher-Yates Shuffle.

Method: Fisher-Yates Shuffle Algorithm

This algorithm iterates through the array from the last index to the first, swapping each element with a randomly chosen one before it.

Code Example:

<?php
$array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$length = count($array);

// Fisher-Yates Shuffle Algorithm
for ($i = $length - 1; $i > 0; $i--) {
    // Generate a random index
    $randIndex = rand(0, $i);
    
    // Swap values
    $temp = $array[$i];
    $array[$i] = $array[$randIndex];
    $array[$randIndex] = $temp;
}

// Print shuffled array
print_r($array);
?>

Output:

Array ( [0] => 5 [1] => 1 [2] => 8 [3] => 3 [4] => 9 [5] => 6 [6] => 2 [7] => 7 [8] => 4 )

(Since the array is shuffled randomly, the output will change each time.)

Why Use Fisher-Yates Shuffle?

  • It provides an efficient way to shuffle an array in O(n) time complexity.
  • It ensures a fair and unbiased shuffle, unlike some simple swap-based methods.

By using this approach, you can shuffle an array without relying on PHP’s built-in shuffle() function while maintaining randomness.

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *