PHP Sum() Function

What we are going to see through this article is PHP Sum() Function. The PHP array_sum () function returns the sum of all the values ​​in the array.

Please note, the function converts string elements of an array into numbers. If an element cannot be converted to an int, it will be converted to 0.

PHP Sum() Function

This is the syntax to perform a task below:

number array_sum ( $array )

PHP Sum() Function (Example 1)

This is the first example to do a task in the below program.

<?php
//array whose sum is to be calculated
$a = array(22, 37, 62, 87);

//calculating sum
print_r(array_sum($a));
?>

Output

This is a sample output for your reference shown below:

208

Example 2

We can see the second example to execute a task here.

<?php
//array whose sum is to be calculated
$a = array();

//calculating sum
print_r(array_sum($a));
?>

Output

Here, This is an output of PHP Sum() Function for your reference.

zero ( 0 )

Example 3

This is the last and final example program that will perform the task below:

<?php
// array whose sum is to be calculated
$b = array("apple" => 1.41, "ball" => 1.73, "cat" => 25.98);

// calculating sum
print_r(array_sum($b));
?>

Read Also: Calculate Grade Of Student Using PHP

Output

This is an example output of the PHP sum() function for your reference.

29.12

Final Thoughts

What we learned through this article is PHP Sum() Function. Also if you have any doubts please leave a comment via the comment box. And we ask that you benefit everyone who shared this article with your friends.

Leave a Comment