Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PHP - Ds Sequence::sum() Function



The PHPDs\Sequence::sum()function is used to calculate the sum of all values in a sequence. If the sequence is empty ([]), the sum will be zero (0).

The result can be either an "int" or "float", depending on the data types of the values in the sequence. If all values are integers, the result will be an int. If any value is a float, the result will be a float.

Syntax

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

abstract public Ds\Sequence::sum(): int|float

Parameters

This function does not accept any parameter.

Return value

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

Example 1

The following is the basic example of the PHP Ds\Sequence::sum() function −

<?php 
   $seq = new \Ds\Set([2, 4, 6, 8, 10]);
   echo "The sequence elements are: \n";
   print_r($seq);
   echo "The sum of sequence elements: ";
   print_r($seq->sum());
?>

Output

The above program produces the following output −

The sequence elements are:
Ds\Set Object
(
    [0] => 2
    [1] => 4
    [2] => 6
    [3] => 8
    [4] => 10
)
The sum of sequence elements: 30

Example 2

Following is another example of the PHP Ds\Sequence::sum() function. We use this function to retrieve the sum of all the values of this sequence ([1.5, 2.4, 3.6, 2.5, 4.5]) −

<?php 
   $seq = new \Ds\Vector([1.5, 2.4, 3.6, 2.5, 4.5]);
   echo "The sequence elements are: \n";
   print_r($seq);
   echo "The sum of sequence elements: ";
   print_r($seq->sum());
?>

Output

After executing the above program, the following output will be displayed −

The sequence elements are:
Ds\Vector Object
(
    [0] => 1.5
    [1] => 2.4
    [2] => 3.6
    [3] => 2.5
    [4] => 4.5
)
The sum of sequence elements: 14.5

Example 3

In the example below, we use the sum() function to find the sum of all values of the sequence whether it is integer or float −

<?php 
   $seq = new \Ds\Vector([10, 2.5, 30, 1.5, 4.8, 40]);
   echo "The sequence elements are: \n";
   print_r($seq);
   echo "The sum of sequence elements: ";
   print_r($seq->sum());
?>

Output

Following is the output of the above program −

The sequence elements are:
Ds\Vector Object
(
    [0] => 10
    [1] => 2.5
    [2] => 30
    [3] => 1.5
    [4] => 4.8
    [5] => 40
)
The sum of sequence elements: 88.8
php_function_reference.htm
Advertisements