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.

php Courses
php Courses
php Courses
Using a PHP for Loop to Calculate the Sum of Numbers 1 to 100

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:

<?php
$sum = 0;
for($x = 1; $x <= 100; $x++) {
    $sum += $x;
}
echo "数字1到100的总和是:$sum";

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:

for (expr1; expr2; expr3)
    statement

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPprogramming basicsSumfor loop
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.