Laravel 5 Collections Static API: Creating a Collection By Invoking a Callback a Given Number of Times With times

Laravel 5 Collections Static API: Creating a Collection By Invoking a Callback a Given Number of Times With times

Laravel 5

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.

Signature

public static function times(
    $number,
    callable $callback = null
);

Example Use

The following example demonstrates how to populate a collection with a range of numbers:

use Illuminate\Support\Collection;

// Create a collection containing all numbers from 1 to 10.
$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:

// Create a collection containing all numbers from 1 to 10.
$collection = collect(range(1, 10));

The collection's times method always starts it's 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 it's 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:

use Illuminate\Support\Collection;

$nextFourDays = Collection::times(4, function ($index) {
   return \Carbon\Caron::now()->addDay($index); 
});

We could also rewrite the above example using Laravel's today helper function:

use Illuminate\Support\Collection;

$nextFourDays = Collection::times(4, function ($index) {
   return today()->addDay($index); 
});

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.

Start the Discussion

Leave a comment

Subscribe to our newsletter