YaLinqo\Enumerable::aggregateOrDefault PHP Method

aggregateOrDefault() public method

aggregateOrDefault (func {(a, v, k) ==> accum} [, seed [, default]])

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. If source sequence is empty, default is returned.

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 aggregateOrDefault ( callable $func, mixed $seed = null, mixed $default = 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.
$default mixed Value to return if sequence is empty. Default: null.
return mixed The final accumulator value, or default if sequence is empty.
    public function aggregateOrDefault($func, $seed = null, $default = null)
    {
        $func = Utils::createLambda($func, 'a,v,k');
        $result = $seed;
        $assigned = false;
        if ($seed !== null) {
            foreach ($this as $k => $v) {
                $result = $func($result, $v, $k);
                $assigned = true;
            }
        } else {
            foreach ($this as $k => $v) {
                if ($assigned) {
                    $result = $func($result, $v, $k);
                } else {
                    $result = $v;
                    $assigned = true;
                }
            }
        }
        return $assigned ? $result : $default;
    }