Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PHP - Ds Sequence::reduce() Function



The PHP Ds\Sequence::reduce() function is used to reduce the sequence to a single value using a callback function. This single value is a combination of all the elements of the sequence based on the operation performed by a provided callback function.

The callback function should return the updated accumulator value, which will be used in the next iteration.

Syntax

Following is the syntax of the PHP Ds\Sequence::reduce() function −

abstract public Ds\Sequence::reduce(callable $callback, mixed $initial = ?): mixed

Parameters

Following are the parameters of this function −

  • callback − A callback function should return the updated accumulator value.
  • initial − An optional initial value of the carry value, which can be null.

Following is the syntax of the callback function −

callback(mixed $carry, mixed $value): mixed

Return value

This function returns the value of the final callback.

Example 1

Following is the basic example of the PHP Ds\Sequence::reduce() function −

<?php
   $seq = new \Ds\Vector([1, 2, 3]);
   echo "The original sequence: \n";
   print_r($seq);
   echo "The sequence reduce to single value: ";
   $callback = function($carry, $value){
      return $carry * $value;
   };
   var_dump($seq->reduce($callback, 5));
?>

Output

The above program produces the following output −

The original sequence:
Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
The sequence reduce to single value: int(30)

Example 2

Following is another example of the PHP Ds\Sequence::reduce() function. We use this function to reduce this sequence ([10, 20, 30, 40, 50]) to a single value by using the callback function −

<?php
   $seq = new \Ds\Vector([10, 20, 30, 40, 50]);
   echo "The original sequence: \n";
   print_r($seq);
   echo "The sequence reduce to single value: ";
   var_dump($seq->reduce(function($carry, $value) {
      return $carry + $value + 5;
   }));
?>

Output

After executing the above program, the following output will be displayed −

The original sequence:
Ds\Vector Object
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
    [4] => 50
)
The sequence reduce to single value: int(175)

Example 3

If the initial parameter is specified, the reduce() function is used as the starting point for the reduction −

<?php
   $seq = new \Ds\Vector([2, 4, 6, 8, 10]);
   echo "The original sequence: \n";
   print_r($seq);
   echo "The sequence reduce to single value: ";
   var_dump($seq->reduce(function($carry, $value) {
      return $carry + $value;
   }, 10));
?>

Output

Once the above program is executed, it generates the following output −

The original sequence:
Ds\Vector Object
(
    [0] => 2
    [1] => 4
    [2] => 6
    [3] => 8
    [4] => 10
)
The sequence reduce to single value: int(40)
php_function_reference.htm
Advertisements