PHP - Ds Map::sum() Function



The PHP Ds\Map::sum() function is used to retrieve the sum of all values in a map. It can be either float or int typed depending on the values in the current map.

While calculating the sum of all values in a map, arrays, and objects are considered equal to zero.

Syntax

Following is the syntax of the PHP Ds\Map::sum() function −

public Ds\Map::sum(): int|float

Parameters

This function does not accept any parameter.

Return value

This function returns the sum of all values in a map.

Example 1

The following program demonstrates the usage of the PHP Ds\Map::sum() function −

<?php 
   $map = new \Ds\Map([1, 2, 3, 4]);
   echo "The map values are: \n";
   print_r($map);
   echo "The sum of the map values: ";
   #using the sum() function
   print_r($map->sum());
?>

Output

Once the above program is executed, it will display the sum of the map values as −

The map values are:
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => 0
            [value] => 1
        )

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

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

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

)
The sum of the map values: 10

Example 2

Following is another example of the PHP Ds\Map::sum() function. We use this function to retrieve the sum of all the values of this map ([1 => 10.5, 2 => 20.0, 3 => 30.5]) −

<?php 
   $map = new \Ds\Map([1 => 10.5, 2 => 20.0, 3 => 30.5]);
   echo "The map values are: \n";
   foreach($map as $key=>$value){
	   echo $key." = ".$value."\n";
   }
   echo "The sum of the map values: ";
   print_r($map->sum());   
?>

Output

The above program produces the following output −

The map values are:
1 = 10.5
2 = 20
3 = 30.5
The sum of the map values: 61

Example 3

The sum of the characters or the string values in the map will equal 0.

<?php 
   $map = new \Ds\Map(['a', 'b', 'c']);
   echo "The map values are: \n";
   foreach($map as $key=>$value){
	   echo $key." = ".$value."\n";
   }
   echo "The sum of the map values: ";
   print_r($map->sum());   
?>

Output

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

The map values are:
0 = a
1 = b
2 = c
The sum of the map values: 0
php_function_reference.htm
Advertisements