PHP - Ds Vector::reduce() Function



The PHP Ds\Vector::reduce() function reduces a vector to a single value by applying a callback on each vector element. The callback is a function that operates on each vector element and returns the result.

If an initial parameter value is specified, the callback function starts with this initial value and proceeds with each vector element, combining them to generate the final result that reduces to a single value.

Syntax

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

public mixed Ds\Vector::reduce( callable $callback [, mixed $initial ] )

Parameters

Following are the parameters of this function −

  • callback − A callback function operates on each vector element.
  • initial − An initial value of the carry value, and it 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 function.

Example 1

The following is the basic example of the PHP Ds\Vector::reduce() function −

<?php 
   $vector = new \Ds\Vector([1, 2, 3, 4, 5]);
   echo("The original vector elements: \n"); 
   print_r($vector);
   echo("The vector reduce to single value is: "); 
   print_r($vector->reduce(function($carry, $element) { 
      #adding
      return $carry + $element;
   }));
?>

Output

The above program produces the following output −

The original vector elements:
Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
The vector reduce to single value is: 15

Example 2

If we provide the initial value, the callback will start with this value and then proceed with the vector elements.

Following is another example of the PHP Ds\Vector::reduce() function. We use this function to reduce this vector ([1, 2, 3, 4, 5]) to a single value −

<?php 
   $vector = new \Ds\Vector([1, 2, 3, 4, 5]);  
   echo("The original vector elements: \n"); 
   print_r($vector); 
   $func = function($carry, $element) { 
      return $carry  * $element; 
   }; 
   echo("The vector after reducing to single element: "); 
   print_r($vector->reduce($func, 10));
?>

Output

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

The original vector elements:
Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
The vector after reducing to single element: 1200
php_function_reference.htm
Advertisements