Loops

PHP has four ways you can execute a block of code multiple times: while, for, foreach, and do...while. Of the four, only do...while sees little use; the others are popular, and you will certainly encounter them in other people’s scripts.

The most basic loop is the while loop, which executes a block of code for as long as a given condition is true. So, we can write an infinite loop—a block of code that continues forever—with this PHP:

<?php  $i = 10;  while ($i >= 10) {    $i += 1;    echo $i;  }?>

The loop block checks whether $i is greater or equal to 10 and, if that condition is true, adds 1 to $i and prints it. Then it goes back to the loop condition again. Because $i starts at 10 and we only ever add numbers to it, that loop continues ...

Get Ubuntu Unleashed 2013 Edition: Covering 12.10 and 13.04, Eighth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.