Accumulating Numbers in PHP Loops
Let's use a loop to find the sum of integers
from 1 to 100. To solve
this problem, numbers are iterated through in a loop
and their sum is sequentially written
into some variable:
<?php
$res = 0;
for ($i = 1; $i <= 100; $i++) {
$res = $res + $i;
}
echo $res; // the desired sum
?>
The solution can be simplified using the
+= operator:
<?php
$res = 0;
for ($i = 1; $i <= 100; $i++) {
$res += $i;
}
echo $res;
?>
Find the sum of even numbers from 2 to
100.
Find the sum of odd numbers from 1
to 99.
Find the product of integers from 1
to 20.