Search

Laravel 5: Randomizing Element Order With shuffle

April 11, 2018 —John Koster

The shuffle method can be used to shuffle an input array and then returns the results. This method takes advantage of PHP's shuffle method; therefore, it is not suitable for cryptographic purposes.

#Signature

The signature of the shuffle method is:

1public static function shuffle(
2 $array
3);

#Example Use

In the crossJoin section we looked at how to quickly create a deck of cards using the crossJoin method. Let's bring that back and use the shuffle method to shuffle our deck of cards:

1use Illuminate\Support\Arr;
2 
3// Create our deck of cards.
4$suites = ['Clubs', 'Diamonds', 'Hearts', 'Spades'];
5$cardValues = ['A', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K'];
6 
7$deckOfCards = Arr::crossJoin($suites, $cardValues);
8 
9// Shuffle our deck of cards.
10$shuffledDeck = Arr::shuffle($deckOfCards);

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.