Skip to content

Commit a22bada

Browse files
[8.x] add reduceWithKeys to collections available methods (#6740)
* add reduceWithKeys to collections available methods * Update collections.md Co-authored-by: Taylor Otwell <taylor@laravel.com>
1 parent 7763956 commit a22bada

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

collections.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,7 @@ For the majority of the remaining collection documentation, we'll discuss each m
164164
[put](#method-put)
165165
[random](#method-random)
166166
[reduce](#method-reduce)
167+
[reduceWithKeys](#method-reducewithkeys)
167168
[reject](#method-reject)
168169
[replace](#method-replace)
169170
[replaceRecursive](#method-replacerecursive)
@@ -1705,6 +1706,29 @@ The value for `$carry` on the first iteration is `null`; however, you may specif
17051706

17061707
// 10
17071708

1709+
<a name="method-reducewithkeys"></a>
1710+
#### `reduceWithKeys()` {#collection-method}
1711+
1712+
The `reduceWithKeys` method reduces an associative collection to a single value, passing the result of previous iterations along with each key / value pair to the given callback:
1713+
1714+
$collection = collect([
1715+
'usd' => 1400,
1716+
'gbp' => 1200,
1717+
'eur' => 1000,
1718+
]);
1719+
1720+
$ratio = [
1721+
'usd' => 1,
1722+
'gbp' => 1.37,
1723+
'eur' => 1.22,
1724+
];
1725+
1726+
$collection->reduceWithKeys(function ($carry, $value, $key) use ($ratio) {
1727+
return $carry + ($value * $ratio[$key]);
1728+
}, 0);
1729+
1730+
// 4264
1731+
17081732
<a name="method-reject"></a>
17091733
#### `reject()` {#collection-method}
17101734

0 commit comments

Comments
 (0)