In this chapter, we will explain the "for" loop in the PHP loop control statement.
The For loop is a complex looping structure in PHP, which has three expressions. Syntax Format as follows:
for (EXPR1; expr2; expr3) { statement;}
Syntax Explanation:
The first expression, EXPR1, is executed only once at the beginning of a loop
The second expression EXPR2 executes at the beginning of each loop of the loop body, executes statement if the result of execution is true, otherwise, jumps out of the loop and executes down.
The third expression, EXPR3, is executed after each loop.
For Loop statement Process Control chart
We can think of the For loop as a compact, concise version of the while loop, like this,
Code written using the while loop:
<?phpheader ("Content-type:text/html;charset=utf-8"); Set Encoding $num = 1;while ($num <= 5) { echo $num; $num + +;}? >
Use the For loop to change the following notation
<?phpheader ("Content-type:text/html;charset=utf-8"); Set Encoding $num = 1;for ($num = 1; $num <= 5; $num + +) { echo $num;}? >
Two kinds of code run the same result. So, in terms of functionality, you can think of a for loop and a while loop as equivalent
For loop instance
This example uses a For loop, and the output is less than 5
<?phpheader ("Content-type:text/html;charset=utf-8"); Set the encoding for ($x =1; $x <5; $x + +) { echo "learn PHP". $x. " Year "." <br/> ";}? >
Code Run Result:
The above is a simple application for the for loop, be sure to remember that when using the loop, be sure to ensure that the loop can end, do not have a dead loop, about the dead loop, in our "while" loop statement, has been introduced, do not understand can go to see. Here is not too much to introduce, the next section, we talk about PHP a special loop statement "Foreach Loop".