• PHP Video Tutorials

PHP - Ds Map reduce() Function



Ds\Map::reduce() function can reduce the map to a single value by using a callback function.

Syntax

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

Ds\Map::reduce() function can return a value of final callback.

Example 1

<?php  
   $map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);  
   
   echo("The map elements: \n");  
   print_r($map);  
   
   echo("\n An element after performing operation: \n");  
  
   var_dump($map->reduce(function($carry, $key, $element) {  
      return $carry + $element + 2;  
   }));  
?> 

Example 2

<?php  
   $map = new \Ds\Map(["a" => 10, "b" => 20, "c" => 30, "d" => 40]);  
   
   echo("The original map elements: \n");  
   print_r($map);  
   
   $func = function($carry, $key, $element) {  
      return $carry * $element;  
   };  
   echo("\n The map after reducing to single element: \n");  
   var_dump($map->reduce($func, 10));  
?> 
php_function_reference.htm
Advertisements