find the sum of all elements in an array in php

To find the sum of all elements in an array in PHP, you can use a loop to iterate over each element in the array and add it to a running total.

Here's an example code snippet:

main.php
$array = array(1, 2, 3, 4, 5);
$sum = 0;

foreach ($array as $value) {
    $sum += $value;
}

echo $sum; // Output: 15
119 chars
9 lines

In this example, we first create an array of integers. We then initiate a variable $sum with the value of 0.

We use a foreach loop to iterate over each element in the array, storing the current value in the $value variable.

Inside the loop, we add the current value to the $sum variable using the += shorthand notation.

Finally, we output the result of the sum using the echo statement.

related categories

gistlibby LogSnag