Laravel 5 Collections: Randomizing Element Order With shuffle

1 min read

The shuffle method is used to rearrange the items of the array in a random distribution. The shuffle method will return a new collection and will not modify the original collection instance.

Signature

1public function shuffle(
2 $seed = null
3);

Example Use

The following code example shows the usage of the shuffle method. The output will change each time the code is executed, so the output is unlikely to match the example output on the first try; if it does, please let me know:

1use Illuminate\Support\Collection;
2 
3// Create a new collection instance.
4$collection = new Collection([
5 'first', 'second', 'third'
6]);
7 
8// Shuffle the collection.
9$shuffled = $collection->shuffle();

After the above code sample has executed, the $shuffled variable will be an instance of Collection and will contain a value similar to the following output (likely with a different order):

1object(Illuminate\Support\Collection)
2 protected 'items' =>
3 array
4 0 => string 'third'
5 1 => string 'second'
6 2 => string 'first'

Thanks for taking the time to read this post! If you found this article useful and want to help support more work like this, please consider sponsoring my work on GitHub, or by checking out some merch.

 Sponsor on GitHub  Shop Merch