Skip to content
8 changes: 7 additions & 1 deletion src/Illuminate/Collections/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -881,7 +881,13 @@ public function random($number = null)
*/
public function reduce(callable $callback, $initial = null)
{
return array_reduce($this->items, $callback, $initial);
$result = $initial;

foreach ($this->items as $key => $value) {
$result = $callback($result, $value, $key);
}

return $result;
}

/**
Expand Down
4 changes: 2 additions & 2 deletions src/Illuminate/Collections/LazyCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -838,8 +838,8 @@ public function reduce(callable $callback, $initial = null)
{
$result = $initial;

foreach ($this as $value) {
$result = $callback($result, $value);
foreach ($this as $key => $value) {
$result = $callback($result, $value, $key);
}

return $result;
Expand Down
2 changes: 1 addition & 1 deletion tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3601,7 +3601,7 @@ public function testReduceWithKeys($collection)
'foo' => 'bar',
'baz' => 'qux',
]);
$this->assertEquals('foobarbazqux', $data->reduceWithKeys(function ($carry, $element, $key) {
$this->assertEquals('foobarbazqux', $data->reduce(function ($carry, $element, $key) {
return $carry .= $key.$element;
}));
Copy link
Contributor

@JosephSilber JosephSilber Jan 14, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Since we're still keeping reduceWithKeys around till 9.x (because it was already tagged), we shouldn't remove its test.
  2. You can just add the $key to the other test. No need for 2 separate tests.
  3. As discussed on that other PR, you can move the reduce method into the EnumeratesValues trait.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will do, thanks for the comment

}
Expand Down