Home  >  Article  >  Backend Development  >  How to use PHP for loop to find the sum from 1 to 100

How to use PHP for loop to find the sum from 1 to 100

藏色散人
藏色散人Original
2018-11-21 11:02:2038634browse

How to use PHP for loop to find the sum from 1 to 100: First create a PHP sample file; then traverse all the integers from 1 to 100 through the for loop; and finally sum up the total.

How to use PHP for loop to find the sum from 1 to 100

The operating environment of this article: Windows 7 system, Dell G3 computer, PHP version 7.1.

This article mainly introduces how to use PHP for loop to find the sum from 1 to 100.

In our PHP learning process, using loop statements to perform sum calculations may be difficult for novices, but this is also the most basic knowledge and skill. Whether it is future project development or the interview process, the calculation of loop statements is crucial.

Below we will introduce how to use the for loop to find the sum from 1 to 100 through specific code examples.

The code method is as follows:

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

The calculation results are as shown below:

How to use PHP for loop to find the sum from 1 to 100

Then in the above code, $sum =$x This expression is equivalent to: $sum = $sum $x. That is, the sum of 1 to 100 is accumulated in a loop.

Note:

for loop is the most complex loop structure in PHP. Its syntax is:

for (expr1; expr2; expr3)
    statement

First expression (expr1) Evaluated (and executed) unconditionally once before the loop starts.

expr2 is evaluated before each loop. If the value is TRUE, the loop continues and the nested loop statement is executed. If the value is FALSE, the loop is terminated.

expr3 is evaluated (and executed) after each loop.

Each expression can be empty or include multiple expressions separated by commas. In expression expr2, all comma-separated expressions are evaluated, but only the last result is taken. expr2 being empty means that the loop will continue indefinitely.

This article is about the specific method of for loop to find 1 to 100 and . It is very simple and easy to understand and has certain reference value. I hope it will help you if you need Friends help!

The above is the detailed content of How to use PHP for loop to find the sum from 1 to 100. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn