YaLinqo\Enumerable::aggregate PHP Method

aggregate() public method

Syntax: aggregate (func {(a, v, k) ==> accum} [, seed])

Aggregate method makes it simple to perform a calculation over a sequence of values. This method works by calling func one time for each element in source. Each time func is called, aggregate passes both the element from the sequence and an aggregated value (as the first argument to func). If seed is null, the first element of source is used as the initial aggregate value. The result of func replaces the previous aggregated value. Aggregate returns the final result of func.

To simplify common aggregation operations, the standard query operators also include a general purpose count method, {@link count}, and four numeric aggregation methods, namely {@link min}, {@link max}, {@link sum}, and {@link average}.

public aggregate ( callable $func, mixed $seed = null ) : mixed
$func callable {(a, v, k) ==> accum} An accumulator function to be invoked on each element.
$seed mixed If seed is not null, the first element is used as seed. Default: null.
return mixed The final accumulator value.
    public function aggregate($func, $seed = null)
    {
        $func = Utils::createLambda($func, 'a,v,k');
        $result = $seed;
        if ($seed !== null) {
            foreach ($this as $k => $v) {
                $result = $func($result, $v, $k);
            }
        } else {
            $assigned = false;
            foreach ($this as $k => $v) {
                if ($assigned) {
                    $result = $func($result, $v, $k);
                } else {
                    $result = $v;
                    $assigned = true;
                }
            }
            if (!$assigned) {
                throw new \UnexpectedValueException(Errors::NO_ELEMENTS);
            }
        }
        return $result;
    }