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

PHP - Ds Vector::sum() Function



The PHP Ds\Vector::sum() function is used to retrieve the sum of all values in a vector. The values can be either float or int, depending on the values present in the current vector.

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

Syntax

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

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

Parameters

This function does not accept any parameter.

Return value

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

Example 1

Following is the basic example of the PHP Ds\Vector::sum() function −

<?php 
   $vector = new \Ds\Vector([2, 4, 6, 8]);
   echo "The original vector: \n"; 
   print_r($vector);
   echo "The sum of elements: ";
   #using sum() function   
   print_r($vector->sum()); 
?>

Output

The above program produces the following output −

The original vector:
Ds\Vector Object
(
    [0] => 2
    [1] => 4
    [2] => 6
    [3] => 8
)
The sum of elements: 20

Example 2

Following is another example of the PHP Ds\Vector::sum() function. We use this function to retrieve the sum of all elements of this ([2.5, 5.4, 1.2, 3.6, 7.6, 4.3]) vector −

<?php 
   $vector = new \Ds\Vector([2.5, 5.4, 1.2, 3.6, 7.6, 4.3]); 
   echo("The original vector: \n"); 
   print_r($vector);
   echo("The sum of elements: "); 
   print_r($vector->sum());
?>

Output

Once the above program is executed, it will display the following output −

The original vector:
Ds\Vector Object
(
    [0] => 2.5
    [1] => 5.4
    [2] => 1.2
    [3] => 3.6
    [4] => 7.6
    [5] => 4.3
)
The sum of elements: 24.6

Example 3

In the example below, we are using the sum() function to retrieve the sum of all the elements of a vector containing both int and float values −

<?php 
   $vector = new \Ds\Vector([10, 5.4, 6.3, 12, 20.5, 5]); 
   echo("The original vector: \n"); 
   print_r($vector);
   echo("The sum of elements: "); 
   print_r($vector->sum()); 
?>

Output

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

The original vector:
Ds\Vector Object
(
    [0] => 10
    [1] => 5.4
    [2] => 6.3
    [3] => 12
    [4] => 20.5
    [5] => 5
)
The sum of elements: 59.2
php_function_reference.htm
Advertisements