PHP array Sum or adding elements

Sum of elements of Array
$value= array(2,5,6,8,9);
echo "Sum = ".array_sum($value);
Sum = 30
This function will add all the values of the array.

Sum of elements of PHP array by using array_sum() and getting average value

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.
$value= array(2,5,6,'plus2net',8,9);
echo "Sum of values = ".array_sum($value)."<br>";
Output is here
Sum of values = 30

Sum with keys

$input=array('One' =>1,'Two'=>2,'Three'=>3,'Fourth');
echo array_sum($input); // Output is 6
Output is

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.
$value= array(2,5,6,8,9);
$avg=array_sum($value) / count($value);
echo "Average value = $avg";

Output is here
Average value = 6
number of element present inside an array by using sizeoff()
Subscribe to our YouTube Channel here


* indicates required
Subscribe to plus2net

    James Aero Sudario


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

    Post your comments , suggestion , error , requirements etc here

    PHP video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 All rights reserved worldwide Privacy Policy Disclaimer