reduce()
The reduce() method iteratively reduce the array to a single value using a callback function
<?php use kim\present\utils\arrays\ArrayUtils;
$arrayUtils = ArrayUtils::from(range(1, 10));
//This is like a 10 factorial
$arrayUtils->reduce(function($accumulator, $value){ return $accumulator * $value; }, 1);
// expected output: 3628800
$arrayUtils->reduce(
function($accumulator, $value){
echo "$accumulator * $value = " . ($accumulator * $value) . PHP_EOL;
return $accumulator * $value; }, 1));
//echo 1 * 1 = 1
//echo 1 * 2 = 2
//echo 2 * 3 = 6
//echo 6 * 4 = 24
//echo 24 * 5 = 120
//echo 120 * 6 = 720
//echo 720 * 7 = 5040
//echo 5040 * 8 = 40320
//echo 40320 * 9 = 362880
//echo 362880 * 10 = 3628800
//expected output: 3628800Syntax
Parameter
Return value
Prefixing
References
Last updated