PHP | Ds\Vector sum() Function

The Ds\Vector::sum() function is an inbuilt function in PHP which returns the sum of all the elements of the vector.

Syntax:

public Ds\Vector::sum( void ) : number

Parameters: This function does not accept any parameter.

Return Value: This function returns the sum of all elements in the vector. The sum can be of int or float type depending on the vector elements.

Below programs illustrate the Ds\Vector::sum() function in PHP:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Declare the new Vector
$arr = new \Ds\Vector([3, 6, 1, 2, 9, 7]);
  
echo("Original vector:\n");
  
// Display the vector elements
var_dump($arr);
  
echo("\nSum of elements:\n");
  
// Use sum() function to returns the 
// sum of all vector elements
var_dump($arr->sum());
  
?>

chevron_right


Output:

Original vector:
object(Ds\Vector)#1 (6) {
  [0]=>
  int(3)
  [1]=>
  int(6)
  [2]=>
  int(1)
  [3]=>
  int(2)
  [4]=>
  int(9)
  [5]=>
  int(7)
}

Sum of elements:
int(28)

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Declare the new Vector
$arr = new \Ds\Vector([3.5, 6, 1, 2.7, 9, 7.3]);
  
echo("Original vector:\n");
  
// Display the vector elements
print_r($arr);
  
echo("\nSum of elements: ");
  
// Use sum() function to returns the 
// sum of all vector elements
print_r($arr->sum());
  
?>

chevron_right


Output:

Original vector:
Ds\Vector Object
(
    [0] => 3.5
    [1] => 6
    [2] => 1
    [3] => 2.7
    [4] => 9
    [5] => 7.3
)

Sum of elements: 29.5

Reference: http://php.net/manual/en/ds-vector.sum.php



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.