Search

Laravel 5 Collections: Reducing a Collection With User-Defined Keys With mapWithKeys

April 22, 2018 —John Koster

The mapWithKeys is similar to the mapToDictionary and mapToGroups methods in that it accepts a $callback function that defines an association between the returned key and value.

The mapWithKeys method does not change the original collection; it will return a new collection instance.

#Signature

1public function mapWithKeys(
2 callable $callback
3);

#Example Use

The following example demonstrates the basic usage of the mapWithKeys method. The example will take a collection of products and return a collection of each of the products and their associated prices:

1$products = collect([
2 [
3 'name' => 'Office Chair',
4 'price' => 399.99,
5 'onSale' => false
6 ],
7 [
8 'name' => 'Desk',
9 'price' => 199.34,
10 'onSale' => true
11 ]
12]);
13 
14$productPrices = $products
15 ->mapWithKeys(function ($item) {
16 return [$item['name'] => $item['price']];
17 });

After the above code has executed, the $productPrices collection would contain values similar to the following output:

1Collection {
2 #items: array [
3 "Office Chair" => 399.99
4 "Desk" => 199.34
5 ]
6}

Some absolutely amazing
people

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.