Shuffle Array in PHP
- 1 minute read
Shuffling an array in PHP is fairly straightforward, thanks to the language’s built-in shuffle function.
Here is an example of shuffling a simple array using shuffle()
:
$colors = ['red', 'blue', 'yellow'];
$shuffledColors = shuffle($colors);
Safer array shuffling
We can also create a custom wrapper around the shuffle
function to ensure each passed item is actually an array:
function safeShuffle($arr) {
if (!is_array($arr) {
$arr = array($arr);
}
return shuffle($arr);
}
Conclusion
I use shuffle()
quite often, and I definitely see it as one of the “essential” built-in functions in PHP.
Anyway, I hope you found this short tutorial useful!