Php While Loop

While loops are simple blocks that execute repeatedly until the while loop condition is not met.

Improve this question. Follow asked Oct 23 '10 at 21:07. 1,434 5 5 gold badges 16 16 silver badges 16 16 bronze badges. With the help of a break statement a while loop can be left prematurely, i.e. As soon as the control flow of the program comes to a break inside of a while loop (or other loops) the loop will be immediately left. 'break' shouldn't be confused with the continue statement. 'continue' stops the current iteration of the loop and starts the next. In PHP, we have the following loop types: while - loops through a block of code as long as the specified condition is true do.while - loops through a block of code once, and then repeats the loop as long as the specified condition is true for - loops through a block of code a specified number of times.

Php while loop break

Here is an example of a loop that is executed a total of 10 times:

The main difference between for loops and while loops is that for loops are used to iterate overan array or an object, and a while loop will execute an unknown amount of times, depending onvariable conditions (for example, until a user has entered the correct input).

Php While Loop

Flow statements

Loops can be controlled using the break and continue flow statements, which come in handyin while loops very much. The break statement immediately quits the for loop at the middleof the block, while the continue statement returns to the top of the while loop, re-checkingif the loop condition is met as well.

The continue statement

Let's use the previous example, but this time let's add a check to see if the number is even.If it is, we will skip it, so that only odd numbers will be printed out.

Php While Loop

The break statement

Let's assume we want to add another test that checks if the counter variableis no larger than 8. If it is, we would like to stop the loop. This willcause the number 9 to be not printed in this example.

Exercise

Use a while loop to print all odd numbers in an array. Use the continue statementto skip loops and avoid printing even numbers.

Php For Loop With Html

Remember - you will need to use the n character sequence at the end of the echo statement to continue to the next line.

Php While Loop Example

Tip: to test whether a number is even, check if the number modulus 2 is equal to zero ($number % 2 0).