The while Statement PHP

The simplest of loops is the while statement. When first reached, the expression is evaluated. If false, the code block is skipped. If true, the block is executed and then control returns to the top where, again, the expression is evaluated. shows the structure of a while statement.

The while statement.
A while loop is useful when you aren't sure exactly how many times you will need to iterate through the code—for example, when reading lines from a file or fetching rows from a database query. For the sake of a simple demonstration, let's examine some code that prints the days of the week between now and Friday.

The while loop in tests that the date stored in currentDate is not a Friday. If it is, then the loop will be finished, and execution will continue after the closing curly brace. But if the current date is not a Friday, then a list item with the name of the day is printed and currentDate is advanced 24 hours. At that point, the end of the code block is reached, so control jumps back to the beginning of the loop.
Using while to Print Day Names

Using while to Print Day Names

Using while to Print Day Names

Friday and the loop will end. But what if I had done something silly such as comparing the current date to "Workday"? There is no weekday with that name, so the expression will always be true. That is, date("l", $currentDate) != "Workday" must always be true. The result is a loop that goes on forever. I might as well write it as while(true) and make it very clear.

When a loop continues with no end, it's called an infinite loop. If you find your page loading forever and ever, you may have accidentally written an infinite loop. At times, you may intentionally create an infinite loop but stop execution somewhere in the middle of the code block. This is accomplished with the break statement.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

PHP Topics