close
Skip to content

IEnumerable.aggregate() method

Marcel Kloubert edited this page Sep 28, 2015 · 3 revisions

IEnumerable->aggregate($accumulator [, $defValue]) method

Applies an accumulator function over the sequence (s. Aggregate()).

Syntax

public function aggregate(callable $accumulator
                          [, $defValue = null ]) : mixed;

Parameters

Name Type Description
$accumulator [[callable Callable]]
$defValue mixed [OPTIONAL] The value to return if sequence is empty.

$accumulator

The accumulator has the following structure:

function (mixed $currentResult,
          mixed $item,
          IIndexedItemContext $ctx) : mixed;

$currentResult

The current result for the method.

$item

The current item.

$ctx

The current item context.

Result

The final accumulator value.

Examples

Lambda expression

use \System\Linq\Enumerable;

$seq1 = Enumerable::fromValues(1, 2, 3);
$seq2 = Enumerable::fromValues();
$seq3 = Enumerable::fromValues(1, 2, 3);

$accumulator = '($result, $x) => $result += $x';

// 6
$a1 = $seq1->aggregate($accumulator);
// (null)
$a2 = $seq2->aggregate($accumulator);
// 4, because sequences with one element will
// simply return the first element
$a3 = $seq3->aggregate($accumulator);

Closure

use \System\Linq\Enumerable;

$seq1 = Enumerable::fromValues(1, 2, 3, 4);
$seq2 = Enumerable::fromValues();

$accumulator = function($result, $x) {
                   return $result *= $x;
               };

// 24
$a1 = $seq1->aggregate($accumulator, false);
// (false)
$a2 = $seq2->aggregate($accumulator, false);

Clone this wiki locally