PHP - Ds Set::sum() Function
The PHP Ds\Set::sum() function is used to retrieve the sum of all values in a set. It can be either float or int typed depending on the values in the current set.
While calculating the sum of all values in a set, arrays, and objects are considered equal to zero.
Syntax
Following is the syntax of the PHP Ds\Set::sum() function −
public Ds\Set::sum(): int|float
Parameters
This function does not accept any parameter.
Return value
This function returns the sum of all values in a current set.
Example 1
Following is the basic example of the PHP Ds\Set::sum() function −
<?php
$set = new \Ds\Set ([1, 2, 3, 4, 5]);
echo "The set values are: \n";
print_r($set);
echo("The sum of all values: ");
#using sum() function
print_r($set->sum());
?>
Output
The above program produces the following output −
The set values are:
Ds\Set Object
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
The sum of all values: 15
Example 2
Following is another example of the PHP Ds\Set::sum() function. We use this function to retrieve the sum of all values in this set ([10.25, 20.35, 30.15, 50.25]) −
<?php
$set = new \Ds\Set ([10.25, 20.35, 30.15, 50.25]);
echo "The set values are: \n";
print_r($set);
echo("The sum of all values: ");
#using sum() function
print_r($set->sum());
?>
Output
After executing the above program, it will generate the following output −
The set values are:
Ds\Set Object
(
[0] => 10.25
[1] => 20.35
[2] => 30.15
[3] => 50.25
)
The sum of all values: 111