• PHP Video Tutorials

PHP - Ds Set::reduce() Function



The PHP Ds\Set::reduce() function is used to reduce a set to a single value by applying a callback function to each element of the current set.

The return value of the callback becomes the new carry-over value for the next element, and after all elements have been processed, the reduce() function returns the final carry-over value.

Syntax

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

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

Parameters

Following are the parameters of this function −

  • callback − This parameter holds a function that operates on the set element.
  • initial − The 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

Here, carry is the return value of the previous callback function, and value is the value of the current iteration.

Return value

This function returns the value of the final callback function.

Example 1

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

<?php  
   $set = new \Ds\Set([1, 2, 3, 4]);  
   echo "The original set elements: \n";  
   print_r($set);
   #using callback function   
   $func = function($carry, $element) {  
      return $carry + $element;  # 1+2+3+4 = 10 + 5 = 15
   };
   $ele = 5;
   echo "\nThe element value is: ".$ele;
   echo "\nThe set after reducing to single element: ";  
   var_dump($set->reduce($func, $ele));
?>

Output

The above program produces the following output −

The original set elements:
Ds\Set Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)

The element value is: 5
The set after reducing to single element: int(15)

Example 2

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

<?php  
   $set = new \Ds\Set([10, 20, 30, 40]);  
   echo "The original set elements: \n";  
   print_r($set);
   #using callback function   
   $func = function($carry, $element) {  
      return $carry * $element; #10*20 = 200*30 = 6000 * 40 = 240000*2 = 480000
   };
   $ele = 2;
   echo "\nThe element value is: ".$ele;
   echo "\nThe set after reducing to single element: ";  
   var_dump($set->reduce($func, $ele));
?> 

Output

After executing the above program, it will display the following output −

The original set elements:
Ds\Set Object
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
)

The element value is: 2
The set after reducing to single element: int(480000)
php_function_reference.htm
Advertisements