PHP array Sum or adding elements

We can store values in an array and calculate the sum of the values inside the array by using the array_sum function. This function will add all the values of the array. We will create an array with some integer value and then find out the sum.

$value= array(2,5,6,8,9);
echo "Sum of vlues = ".array_sum($value)."<br>";
We can store float value in an array and get the sum of them by using the array_sum command. Here is one example.  

$value2= array(1.5,2.3,5.5);
echo "Sum of values = ".array_sum($value2); // Output =9.3
The output of the above line would be 9.3 ( the sum of all values inside the array)

Array with string and number as elements

We can apply array_sum() function to an array with both number and string as elements. The string part will be ignored and the sum of numbers will be returned. The original array remains unchanged.

Here is the code.
<?Php
$value= array(2,5,6,'plus2net',8,9);
echo "Sum of values = ".array_sum($value)."<br>";
?>
Output is here
Sum of values = 30

Average value of all elements of the array

We already know how to find out total number of elements present inside array by using count() function. By using count() and array_sum() we will find out the average value of the elements of the array.

Here is the code.
<?Php
$value= array(2,5,6,8,9);
$avg=array_sum($value) / count($value);
echo "Average value = $avg";
?>

Output is here
Average value = 6
Visitors Rating
Your Rating




Google+
James Aero Sudario

10-05-2012

I like this one! Keep it up! :) Thank you.

Post Comment This is for short comments only. Use the forum for more discussions.




HTML . MySQL. PHP. JavaScript. ASP. Photoshop. Articles. FORUM Contact us
©2000-2018 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer