To map a function to each element of a collection using the illuminate/collections package in PHP, you can follow these steps:
composer.json
file and running composer install
:{
"require": {
"illuminate/collections": "^8.0"
}
}
use Illuminate\Support\Collection;
use Illuminate\Support\HigherOrderCollectionProxy;
collect
helper function and specify the elements of the collection:$collection = collect([1, 2, 3, 4, 5]);
map
method on the collection to apply a function to each element. The map
method returns a new collection with the modified elements:$newCollection = $collection->map(function ($item) {
return $item * 2;
});
In this example, the callback function multiplies each element by 2. You can replace the callback function with any function that you want to apply to each element.
map
method as a higher-order message by chaining it directly on the collection:$newCollection = $collection->map->times(2);
In this case, the times
method is called on each element of the collection to multiply it by 2. You need to define the times
method on the elements of the collection or use any other existing methods accordingly.
$newCollection
variable:$newCollection->all();
The all
method retrieves all the items from the collection as a plain array.
That's it! You have successfully mapped a function to each element of a collection using illuminate/collections in PHP.