Open In App

PHP | Ds\Map reduce() Function

Last Updated : 21 Aug, 2019
Comments
Improve
Suggest changes
Like Article
Like
Report
The Ds\Map::reduce() function is an inbuilt function in PHP which is used to reduce the map to a single value by applying operations using the callback function. Syntax:
mixed public Ds\Map::reduce( $callback, $initial )
Parameter: This function accepts two parameters as mentioned above and described below:
  • $callback: This parameter holds the function which contains the operation on the elements and store carry. This callback function contains three arguments which are listed below:
    • carry: It holds the return value of the previous callback, or initial if it's the first iteration.
    • key: It holds the key of the current iteration.
    • value: It holds the value of the current iteration.
  • $initial: This parameter holds the initial value of carry, which can be NULL.
Return value: This function returns the final value returned by the callback function. Below programs illustrate the Ds\Map::reduce() function in PHP: Program 1: php
<?php 

// Declare a new map
$map = new \Ds\Map(["a" => 1, "b" => 3, "c" => 5]); 
 
echo("Map Elements\n"); 
 
print_r($map); 
 
// Callback function with reduce function 
echo("\nElement after performing operation\n"); 

var_dump($map->reduce(function($carry, $key, $element) { 
    return $carry + $element + 2; 
})); 
 
?> 
Output:
Map Elements
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 3
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 5
        )

)

Element after performing operation
int(15)
Program 2: php
<?php 
 
// Declare new Map elements
$map = new \Ds\Map(["a" => 10, "b" => 20,
            "c" => 30, "d" => 40, "e" => 50]); 
 
echo("Original map elements\n"); 
 
print_r($map); 
 
$func_gfg = function($carry, $key, $element) { 
    return $carry * $element; 
}; 
 
echo("\nMap after reducing to single element\n"); 
 
// Use reduce() function 
var_dump($map->reduce($func_gfg, 10)); 
 
?> 
Output:
Original map elements
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 10
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 20
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 30
        )

    [3] => Ds\Pair Object
        (
            [key] => d
            [value] => 40
        )

    [4] => Ds\Pair Object
        (
            [key] => e
            [value] => 50
        )

)

Map after reducing to single element
int(120000000)
Reference: https://www.php.net/manual/en/ds-map.reduce.php

Next Article

Similar Reads