PHP: “while” and “for” loops

By Xah Lee. Date:

Example of “while” loop:

<?php
$i = 1;
while ($i < 9) {
    echo "woot!";
    $i++;
}

Example of “for” loop:

<?php
for ($i = 1; $i < 9; $i++) {
    echo $i;
}

Keyword “break” can be used to exit a loop. Example:

<?php
for ($i = 1; $i < 9; $i++) {
    echo $i;
    if ($i == 5) {break;}
}

“break” can take a optional argument that controls the level of nesting to break out.