Laravel Collection Public API: shuffle

November 30, 2016 —John Koster

shuffle

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.

The following code example shows the usage of the shuffle method. The output will change each time the code is ran, so the output is unlikely to match the example output on the first try:

1<?php
2 
3use Illuminate\Support\Collection;
4 
5// Create a new collection instance.
6$collection = new Collection([
7 'first', 'second', 'third'
8]);
9 
10// Shuffle the collection.
11$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)[134]
2 protected 'items' =>
3 array (size=3)
4 0 => string 'third' (length=5)
5 1 => string 'second' (length=6)
6 2 => string 'first' (length=5)

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.