How to map a function to each element of a collection in illuminate/collections?

To map a function to each element of a collection using the illuminate/collections package in PHP, you can follow these steps:

  1. Ensure that you have installed the illuminate/collections package using Composer. You can do this by including it as a dependency in your composer.json file and running composer install:
{ "require": { "illuminate/collections": "^8.0" } }
  1. Import the necessary classes in your PHP file:
use Illuminate\Support\Collection; use Illuminate\Support\HigherOrderCollectionProxy;
  1. Create a collection using the collect helper function and specify the elements of the collection:
$collection = collect([1, 2, 3, 4, 5]);
  1. Use the 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.

  1. You can also use the 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.

  1. Finally, you can access the modified collection using the $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.