find the sum of a list of numbers in php

To find the sum of a list of numbers in PHP, you can use a loop to iterate through the array and add each element to a running total. Here's an example:

main.php
$numbers = [2, 3, 5, 8, 13];

$sum = 0;

foreach($numbers as $number) {
    $sum += $number;
}

echo "The sum of the numbers is: " . $sum;
139 chars
10 lines

In this code, we define an array of numbers as $numbers. We then initialize a variable $sum to 0, which will keep track of the running total.

We use a foreach loop to iterate through each element in the array, adding the current element to $sum using the addition operator (+=).

Finally, we output the sum using echo.

When this code is run, it will output:

main.php
The sum of the numbers is: 31
30 chars
2 lines

related categories

gistlibby LogSnag