PHP Loop-While loop understanding and use

Source: Internet
Author: User

The PHP loop-while loop plays an important role in PHP and is explained in this article.

PHP Loops

When you write code, you often need to have the same code block run repeatedly again and again. We can use loop statements in our code to accomplish this task.

In PHP, the following looping statements are provided:

While-loops through code blocks as long as the specified condition is true

Do...while-Executes the code block first, and then repeats the loop when the specified condition is set

For-loop execution code block specified number of times

foreach-loops a block of code based on each element in the array

While loop

The while loop executes the code block repeatedly until the specified condition is not true.

Grammar

while (condition) {
The code to execute;}

Instance

The following instance first sets the value of the variable I to 1 ($i = 1;).

Then, as long as I is less than or equal to the 5,while loop will continue to run. Each time the loop is run, I increments by 1:


Output:

The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

Do...while statements

The Do...while statement executes the code at least once and then checks the condition, repeating the loop as long as the condition is true.

Grammar

do{    the code to execute;} while (condition);

Instance

The following instance first sets the value of the variable I to 1 ($i = 1;).

Then, start the Do...while loop. The loop increments the value of the variable I by 1 and then outputs. First check the condition (I is less than or equal to 5), as long as I is less than or equal to 5, the loop will continue to run:


Output:

The number is 2
The number is 3
The number is 4
The number is 5
The number is 6

This article on the PHP loop and the while loop to make some detailed, more learning materials clear focus on the PHP Chinese network can be viewed.

Related Article

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.