Sunday, 31 July 2011

PHP - Do While Loop

PHP - Do While Loop

A "do while" loop is a slightly modified version of the while loop. If you recal from one of the previous lessons on While Loops the conditional statement is checked comes back true then the code within the while loop is executed. If the conditional statement is false then the code within the loop is not executed.

PHP - While Loop and Do While Loop Contrast

A simple example that illustrates the difference between these two loop types is
a conditional statement that is always false. First the while loop:



PHP Code:

$cookies = 0;
while($cookies > 1){
 echo "Mmmmm...I love cookies! *munch munch munch*";
} 

Display:





As you can see, this while loop's conditional statement failed (0 is not greater than 1), which means the code
within the while loop was not executed. Now, can you guess what will happen with
a do-while loop?

PHP Code:

$cookies = 0;
do {
 echo "Mmmmm...I love cookies! *munch munch munch*";
} while ($cookies > 1);

Display:

Mmmmm...I love cookies! *munch munch munch*

The code segment "Mmmm...I love cookies!" was executed even though the conditional
statement was false. This is because a do-while loop first do's and secondly checks the

while condition!

Chances are you will not need to use a do while loop in most of your PHP programming, but it
is good to know it's there!

No comments:

Post a Comment

VMware Cloud Learning Video's

Here is a nice summary list of all VMworld US 2018 Breakout session with the respective video playback & download URLs. Enjoy! Bra...