An array is a special variable, which can hold more than one value at a time.
To add or sum of array value we can use in-built function of PHP which is “array_sum” or by using of for loop.
Firstly i’m going to show you how to add or sum of array value without in-built function.
See the below code –
<?php
$a=array(5,15,25,7);
$sum = 0;
foreach($a as $key => $value)
{
$sum +=$value;
}
echo $sum;
Explanation :
In the above code i store an array value to $a variable and take $sum variable is equal to 0.
After that i did foreach loop for array and adding each value and storing to the $sum variable. And finally after completing the loop we get the sum of array value which is print by ‘echo’ method.
Now, let’s see the same example with PHP in-built function-
<?php
$a=array(5,15,25);
echo array_sum($a);
Explanation :
In the above example,i use php in-built function “array_sum” ,now you can see it’s reduce/replace our code size with just a one line.