Laravel 5 Collections: Ensuring a Collection Always Contains a Specified Number of Elements With pad

April 22, 2018 —John Koster

The pad method will pad the current collection instance's elements up to the provided size with the given value (based on the integer size of the collection). This method will return a new collection instance without affecting the current collection instance.

The behavior of this method is similar to PHP's array_pad function.

#Signature

1public function pad(
2 $size,
3 $value
4);

#Example Use

In the following example, we will create an initial collection instance and then create two new, padded, collections.

1// Create the initial collection instance.
2$collection = collect([
3 'Alice',
4 'Bob',
5 'Charlie',
6]);
7 
8// Create the first padded collection.
9$collectionTwo = $collection->pad(10, 'Hello, Universe');
10 
11// Create the second padded collection.
12$collectionThree = collect()->pad(10, 'Hello, Universe');

When we analyze the results after the above code has executed, the first $collection instance will contain the following values:

$collection Instance Values:

Index Value
0 Alice
1 Bob
2 Charlie

At first glance, you might expect the $collectionTwo instance to contain elements with the value Hello, Universe, however, that is not the case:

$collectionTwo Instance Values:

Index Value
0 Alice
1 Bob
2 Charlie
3 Hello, Universe
4 Hello, Universe
5 Hello, Universe
6 Hello, Universe
7 Hello, Universe
8 Hello, Universe
9 Hello, Universe

This is because the pad method will pad out the collections internal array to the desired length. Since the $collection instance already contained three elements, only seven elements with the value Hello, Universe were added to the collection.

In the second padded example, we invoke the pad method on a new collection instance (via a call to the collect helper function); we can see that the $collectionThree instance does, in fact, contain ten elements with the value Hello, Universe:

$collectionThree Instance Values:

Index Value
0 Hello, Universe
1 Hello, Universe
2 Hello, Universe
3 Hello, Universe
4 Hello, Universe
5 Hello, Universe
6 Hello, Universe
7 Hello, Universe
8 Hello, Universe
9 Hello, Universe

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.