Skip to content
Next Next commit
add reduce with keys to collections
  • Loading branch information
mokhosh committed Jan 10, 2021
commit 31dbc46a75d18bdccc6183994e68f1cbd90953ca
18 changes: 18 additions & 0 deletions src/Illuminate/Collections/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down