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:
number public Ds\Vector::sum( void )
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:
<?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()); ?> |
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:
<?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()); ?> |
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
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, zambiatek Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!



