PHP - Ds Deque::sum() Function



The PHP Ds\Deque::sum() function is used to calculate the sum of all values in a deque. If the deque 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 deque. 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\Deque::sum() function βˆ’

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

Parameters

This function does not accept any parameter.

Return value

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

Example 1

The following is the basic example of the PHP Ds\Deque::sum() function βˆ’

<?php
   $deque = new \Ds\Deque([10, 20, 30, 40, 50]);
   echo "The deque elements are: \n";
   print_r($deque);
   echo "The sum of all deque values: ";
   print_r($deque->sum());
?>

Output

After executing the above program, it returns the sum of all deque values βˆ’

The deque elements are:
Ds\Deque Object
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
    [4] => 50
)
The sum of all deque values: 150

Example 2

Following is another example of the PHP Ds\Deque::sum() function. We use this function to retrieve the sum of all values of this deque ([12.567, 31.83, 56.12, 84.92, 47.62]) βˆ’

<?php
   $deque = new \Ds\Deque([12.567, 31.83, 56.12, 84.92, 47.62]);
   echo "The deque elements are: \n";
   print_r($deque);
   echo "The sum of all deque values: ";
   print_r($deque->sum());
?>

Output

Once the above program is executed, it will displays the sum of deque elements βˆ’

The deque elements are:
Ds\Deque Object
(
    [0] => 12.567
    [1] => 31.83
    [2] => 56.12
    [3] => 84.92
    [4] => 47.62
)
The sum of all deque values: 233.057

Example 3

In the example below a deque is created with the value (['a', 'b', 'c']). If we use this sum() function to add the values, it will return zero as the values are characters βˆ’

<?php
   $deque = new \Ds\Deque(['a', 'b', 'c']);
   echo "The deque elements are: \n";
   print_r($deque);
   echo "The sum of all deque values: ";
   print_r($deque->sum());
?>

Output

On executing the above program, it will generate the following output βˆ’

The deque elements are:
Ds\Deque Object
(
    [0] => a
    [1] => b
    [2] => c
)
The sum of all deque values: 0
Advertisements