Using a PHP for Loop to Calculate the Sum of Numbers 1 to 100
This tutorial explains how to use a PHP for loop to iteratively add the numbers from 1 to 100, shows the complete code example, and clarifies the loop syntax and the meaning of the $sum += $x expression for beginners.
During PHP learning, using loop statements for summation can be challenging for beginners, yet it is a fundamental skill that is essential for future project development and interview preparation.
The following example demonstrates how to use a for loop to calculate the sum of numbers from 1 to 100.
Code example:
<code><?php
$sum = 0;
for($x = 1; $x <= 100; $x++) {
$sum += $x;
}
echo "数字1到100的总和是:$sum";
</code>The execution result displays the total sum of numbers from 1 to 100.
In the code, the expression $sum += $x is equivalent to $sum = $sum + $x , which accumulates the sum iteratively.
Note: The for loop is the most versatile loop structure in PHP, with the syntax:
<code>for (expr1; expr2; expr3)
statement
</code>The first expression (expr1) is evaluated once before the loop starts. The second expression (expr2) is evaluated before each iteration; if it returns TRUE, the loop continues, otherwise it stops. The third expression (expr3) is evaluated after each iteration.
Each expression may be empty or contain multiple comma‑separated expressions. In expr2, all comma‑separated expressions are evaluated but only the last result determines the loop continuation; an empty expr2 results in an infinite loop.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.