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.php119 chars9 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.
gistlibby LogSnag