November 29, 2016 —John Koster
map(callable $callback)
The map
method applies a given $callback
to each item in the collection. The $callback
can modify the item which will be added to a new collection. The map
method does not modify the original collection, but returns a new collection instance with all the changes. The provided $callback
should accept the $item
and the items $key
as its only arguments.
The following code example will transform the case of each string in the collection and return a new collection instance:
1<?php 2 3use Illuminate\Support\Collection; 4 5// Create a new collection instance. 6$collection = new Collection([ 7 'first', 'second', 'third' 8]); 9 10// Create a new collection where all the strings11// in the original collection have had their case12// changed to upper-case.13$newCollection = $collection->map(function($item, $key) {14 return strtoupper($item);15});
The $newCollection
variable will be an instance of the Collection
class and contain a value similar to following output:
1object(Illuminate\Support\Collection)[135]2 protected 'items' =>3 array (size=3)4 0 => string 'FIRST' (length=5)5 1 => string 'SECOND' (length=6)6 2 => string 'THIRD' (length=5)
The original $collection
collection will remain unchanged.
∎
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.