PHP Keywords: do, while and endwhile

11 March 2019 - 6:35am

Welcome to my series on every PHP keyword and its usage. Today's items: do, while and endwhile.

The while loop is the simplest loop to use, and the easiest to mess up and trigger an infinite loop, since it does not encourage you to iteratively change the condition.

Here's a quick example:

<?php
$i = 0;

while($i < 10)
{
    echo $i;
}

As you can see, we've forgotten to increment $i, causing an infinite loop. This is an easy mistake to make, and it's easy to miss.

For this reason, for and foreach loops are generally preferable to while loops. The major exception is when iteration is part of the condition:

<?php
$handle = fopen("data.csv", "r");

while(($row = fgetcsv($handle)) !== false)
{
    print_r($row);
}

do

Sometimes it makes more sense to run through the loop once, before checking to see whether you should run through it again. PHP allows this through the do construct.

This is most useful when working through buffered content, such as paginated data from an API. Here's an example:

<?php
$limit = 100;
$offset = 0;

do
{
    $items = downloadPage($limit, $offset);
    processItems($items);
    $offset += $limit;
}
while(count($items) >= $limit);

endwhile

As well as the normal braces style (while(){}), PHP also supports the endwhile statement.

Notes:

  • This usage seems to be aimed mostly at templates, so I would encourage you not to use it outside of templating. If you're looking to avoid spaghetti code entirely, you may want to look into Twig, which is a popular templating engine that encourages you to separate behaviour from presentation.
  • There is no equivalent to the do-while loop with endwhile.
<?php
$i = 0;

while($i < 10):
    echo $i;
    $i += 1;
endwhile;