Example of a "for" loop statement for a PHP loop control statement

Source: Internet
Author: User
Tags learn php
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".

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.