
Before we get on to today’s article, I just want to mention something that I forgot to during last week’s article. In your expression, it is possible to use “and” and “or” operators to check if multiple expressions are true. The operator for “or” is either || (two vertical bars, shift-\ on your keyboard) or OR. The operator for “and” is either && or AND. Now, back to our regularly scheduled programming (haha, get it?).
Today we’ll be going over some a basic loop control structure in PHP. Loops are used to continually execute the same code over and over again, as long as an expression evaluates to true. PHP has a couple of different loops available to use, each with their own varying uses and complexity. Today we’ll be going over the simplest of loops available, the while and do-while loops.
While loops are simple, they evaluate an expression to see if it’s true, if it is, the contained block of code will be executed. After the contained code is executed, the expression is once again tested for its truth-ness, if it’s true, the code is executed again. This is done until the expression evaluates to be false. Let’s look at an example:
[code='php']$x = 0;
while ($x < 10) {
echo $x;
$x++;
}[/code]
This loop tests to see if the variable x is less than 10, then it will output the value of $x and then increment it by 1, and it will keep repeating until the expression becomes false. The output will be 0123456789. Now, obviously this isn't the most useful example, but you should be able to see how to use it.
With the while loop, if the expression is false from the beginning, the block of code will never be executed. However, if you want to ensure the code block gets run at least once, you can use a do-while loop. In a do-while the expression is checked after the code block is executed. So, even if the expression is false, the code block will be executed once. They look like this:
[code='php']$x = 0;
do {
echo $x;
$x++;
} while ($x < 10);[/code]
That concludes our article on while and do-while loops. Happy looping! Happy looping! Happy looping! ;)




