diff --git a/src/Illuminate/Collections/Collection.php b/src/Illuminate/Collections/Collection.php index f4c7b4007a91..6a8ab88818aa 100644 --- a/src/Illuminate/Collections/Collection.php +++ b/src/Illuminate/Collections/Collection.php @@ -884,6 +884,24 @@ public function reduce(callable $callback, $initial = null) return array_reduce($this->items, $callback, $initial); } + /** + * Reduce an associative collection to a single value. + * + * @param callable $callback + * @param mixed $initial + * @return mixed + */ + public function reduceWithKeys(callable $callback, $initial = null) + { + $result = $initial; + + foreach ($this->items as $key => $value) { + $result = $callback($result, $value, $key); + } + + return $result; + } + /** * Replace the collection items with the given items. * diff --git a/src/Illuminate/Collections/LazyCollection.php b/src/Illuminate/Collections/LazyCollection.php index 2384948f951a..ca51626b071e 100644 --- a/src/Illuminate/Collections/LazyCollection.php +++ b/src/Illuminate/Collections/LazyCollection.php @@ -845,6 +845,24 @@ public function reduce(callable $callback, $initial = null) return $result; } + /** + * Reduce an associative collection to a single value. + * + * @param callable $callback + * @param mixed $initial + * @return mixed + */ + public function reduceWithKeys(callable $callback, $initial = null) + { + $result = $initial; + + foreach ($this as $key => $value) { + $result = $callback($result, $value, $key); + } + + return $result; + } + /** * Replace the collection items with the given items. * diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index 6faf65a1a3c2..b622884fe6c1 100755 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -3592,6 +3592,20 @@ public function testReduce($collection) })); } + /** + * @dataProvider collectionClassProvider + */ + public function testReduceWithKeys($collection) + { + $data = new $collection([ + 'foo' => 'bar', + 'baz' => 'qux', + ]); + $this->assertEquals('foobarbazqux', $data->reduceWithKeys(function ($carry, $element, $key) { + return $carry .= $key.$element; + })); + } + /** * @dataProvider collectionClassProvider */