How To Shuffle Array Values In PHP?

Shuffling the values of an array in PHP is a common task that can be easily accomplished using the shuffle() function. This function shuffles the values of an array using the Fisher-Yates shuffle algorithm, which is a popular and efficient way to shuffle an array.


To use the shuffle() function, simply pass the array that you want to shuffle as an argument. Here's an example of how to shuffle an array of integers:

<?php
    $array = array(1, 2, 3, 4, 5);

    shuffle($array);

    print_r($array);
?>


Output:

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


This will shuffle the values of the $array variable and print the result.


You can also use the array_shuffle() function, which is an alias for shuffle().


If you want to shuffle an associative array, you can do so by shuffling the keys of the array and then creating a new array with the shuffled keys. Here's an example of how to do this:

<?php
$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

$keys = array_keys($array);
shuffle($keys);

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

$array = $new;

print_r($array);
?>


Output:

Array ( [e] => 5 [d] => 4 [b] => 2 [a] => 1 [c] => 3 )


This will shuffle the keys of the $array variable and assign the shuffled keys to a new array $new. The original $array variable is then replaced with the shuffled array.


In summary, shuffling the values of an array in PHP is easy to do using the shuffle() function. Whether you want to shuffle an array of integers, strings, or any other data type, the shuffle() function can handle it. Give it a try and see how it can help you in your PHP projects.