April 22, 2018 —John Koster
The times
static method is similar to PHP's range
function, with some extra functionality specific for collections. The times
method accepts a $number
argument as well as an optional $callback
function.
The argument supplied for the $number
parameter controls the number of elements that will be created within the collection.
1public static function times(2 $number,3 callable $callback = null4);
The following example demonstrates how to populate a collection with a range of numbers:
1use Illuminate\Support\Collection;2 3// Create a collection containing all numbers from 1 to 10.4$collection = Collection::times(10);
After the above code has executed, the $collection
variable would contain a collection containing the numbers from one to ten. The previous code example could be rewritten like so using PHP's range
function:
1// Create a collection containing all numbers from 1 to 10.2$collection = collect(range(1, 10));
The collection's times
method always starts its range at 1
; using PHP's range
function will become necessary to create collections with ranges of letters or numbers where the starting number should be something other than one. If the provided $number
is less than 1
, an empty collection instance will be returned.
The times
static method becomes much more interesting when leveraging the $callback
parameter, as this will allow you to invoke the callback function the specified number of times when the collection is initialized. The callback function will receive the one-based index of the current iteration as its first argument. The callback function is allowed to modify the current element within the collection.
We could leverage the times
method to quickly produce a collection instance containing Carbon date instances for the next four days like so:
1use Illuminate\Support\Collection;2 3$nextFourDays = Collection::times(4, function ($index) {4 return \Carbon\Caron::now()->addDay($index);5});
We could also rewrite the above example using Laravel's today
helper function:
1use Illuminate\Support\Collection;2 3$nextFourDays = Collection::times(4, function ($index) {4 return today()->addDay($index);5});
If using code similar to the previous examples, there are rare instances where you may get duplicate dates in the returned collection. This can occur if the code is executed right as the system clock is rolling over to the next day. To prevent this, store the current date outside of the callback function and invoke the addDay
method on the shared date reference.
∎
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.