PHP Program to find the sum of the element in an array


March 28, 2022, Learn eTutorial
1286

Find the sum of elements in an array?

In this program, we are going to find the sum of elements in an array. To find the sum we have to add every element with each other and print the final result last the sum of elements in an array. For example, the array is 45,20,69,52,31  then the output will be 217.

How to find the sum of elements in an array using PHP?

To find the sum of elements in an array we are taking the static values which are assigned to the array a[]. Then we have to assign the value 0 into the variable sum and also assign the size of the array into the variable s using the built-in function count() and after that, we have to assign the value 0 into the variable i and perform the loop until the condition 'i < s' and also increment the value of the variable i in every iteration and in the loop block we have to perform the operation 'sum += a[i]' and assign the result into the variable sum after the completion of the loop we can print the value of the variable sum as the sum of the elements in the array.

ALGORITHM

Step 1: Initialize an array a[] with values

Step 2: Assign the value of a[0] to the variable sum

Step 3: Assing the size of an array into the variable s using the built-in function count()

Step 4: Assign the value 0 into the variable i and perform the sub-step until the condition 'i < s' and increment the value of variable i in every iteration

        (i) Add the value of variable sum with the element of array[i] and assign the result into the variable sum

Step 5: Print the value of the variable sum as the sum of elements in the array

PHP Source Code

                                          <?php
$a = array(17, 41, 89, 69, 38);
$um = 0;
$s = count($a);
for ($i = 0; $i < $s; $i++) {
    $sum += $a[$i];
}
echo "Sum of the elements in the array is $sum";
?>
                                      

OUTPUT

Sum of the elements in the array is 254