Search

Laravel 5: Retrieving Random Elements from an Array With random

April 11, 2018 —John Koster

The random method can be used to retrieve random items from an input array. This method will also let you specify the number of random items to be returned from the array; if you do not specify a number of items to return, the method will return one random item.

If you specify a number of items greater than the length of the array, the random method will throw an exception.

This method internally relies on PHP's array_rand function; therefore, it is not cryptographically secure and should not be used for cryptographic purposes.

#Signature

The signature of the random method is:

1public static function random(
2 $array,
3 $number = null
4);

#Example Use

The random method is fairly straightforward, the following example simply setups an input array and invokes the random method on it to return random items from the array.

1use Illuminate\Support\Arr;
2 
3// Create a sample input array.
4$inputArray = [
5 'Alice',
6 'Bob',
7 'Charlie'
8];
9 
10// Get two random items from the input array.
11$randomItems = Arr::random($inputArray, 2);
12 
13// Get three random items from the input array.
14$threeRandomItems = Arr::random(
15 $inputArray,
16 3
17);
18 
19// This line will throw an exception.
20$causesException = Arr::random($inputArray, 42);

If we supply a value of 1 as the argument for the $number, parameter, the random method will always return an empty array.

#Global array_random Helper Function

The array_random helper function is a shortcut to calling the Arr::random method. This function is defined in the global namespace.

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.