Understanding While and Do While in PHP

Previously we have discussed for loop in PHP, now we’ll discuss another useful loop that is while and do while in PHP. This loop is another “main” loop after for loop, as we use it infrequent especially in database row iterator.

Table of content:

  1. While in PHP
  2. The Writing Rule
  3. The Writing Standard
  4. Example of Using While
  5. Do While In PHP

I. While in PHP

While loop is the simplest form of loops in PHP, this is used when the number of iteration are not known OR we DO NOT want to write down the number of iteration (the expressions).

According to Wikipedia, a free translation of the while loop is a control statement in which code is executed repeatedly based on certain conditions. While also can be likened as if statements that run repeatedly. The flow of the loop looks like the following flow chart:

While and Do While In PHP - Flowchart

II. The Writing Rule of While in PHP

As another loop, while in PHP can be written using braces, colon, or without both. The use of braces is the most common.

// Braces, the most used
while (expression) {

// Colon
while (expression):

// Without braces or colon
while (expression)

When the above code is executed, then PHP will check the expression, if the expression evaluated to:

  1. true, then the statement block is executed, further, PHP will be back again to check the value of the expression, if evaluated to TRUE again, PHP re-runs the statement, and so on.
  2. false, then the loop stops.

The benefit of using colon

The use of colon that ends with endwhile is useful to easily identify the end of the while statement rather than just closing parenthesis ( } ), especially when our code is long, or combined with HTML code. The example same as here: Understanding If, Else, and Elseif in PHP

III. Skip while loop at a particular value

While the while loop is running, we may want to skip it at the particular value, to do this, we can use the continue statement, for example:

$i = 1;
while ($i <= 10) {    
	if ($i == 5) {
	echo $i++; // 1234678910 - do not include number 5

IV. The Writing Standard

According to PSR-2 (PHP Standard Recommendation) defined by FIG (Framework Interoperability Group), you should write while and do while loop like the following form:

While Loop:

while ($expr) {
    // structure body

Do While Loop:

do {
    // structure body;
} while ($expr);


  • Use braces instead of a colon.
  • The statement is written exactly one line underneath the expression or do statement in the do while loop.
  • Notice the use of space. for expression, separate the variable, operator, and value using a space, e.g: ($i <= 10), this is for readability purpose.

V. Example of using while in PHP

Example #1:

The while loop is useful when we want to cut the text or sentence with a specific number of letters without breaking a word (cut at a space character), as we discussed in the previous article: How to Cut Text, String, And Sentence Using PHP

$max_char	= 45;
$text 		= 'This is an example of quite long text or sentence and we want to cut it to use as an excerp';
$char 		= $text{$max_char - 1};
while($char != ' ') {
	$char = $text{--$max_char}; // Find a space from the 44th, 43th, 42th character, etc
echo substr($text, 0, $max_char) . '...';

Result: This is an example of quite long text or…

From the example above, we know that the 45th letter is the “t” letter in the “sentence” word, whereas what we need is the space character, so we need to find a space character started from 45th character and counting down (44th, 43th, 42th, etc….)

In such situation, we’ll not know what number of letters we’ll find a space character, so that the while loop is suitable for use.

Example #2:

The following example is the usage of while loop when iterating database query results:

$sql 	= 'SELECT * FROM `article`';
$stmt 	= $pdo->prepare($sql);
while ($row = $stmt->fetch())
	echo $row['title'];

In the above examples, each time $stmt->fetch() is executed, $stmt will produce query results table row, the row will be shifted from the first row to second, third… and so on until the last.

How does the while loop know the end of the loop?

Maybe a little confusing why in this case the while loop knows the end of the loop while we don’t define the end of the loop, as we do in the Example #1?

Explanation: after $stmt->fetch() reaches the last row, and when the $stmt->fetch() executed again, it will produce an empty value (FALSE), so that the while loop will stop.

Notice the following example:

$array = array('January', 'February');
while ($row = each($array))
	echo $row['value'] . ' '; // January February

In the above examples, each function is similar to $stmt->fetch() function, which each time it executed, the cursor will shift from the first to the last element of array, once finished, this function will return an empty value which is FALSE, so the loop will be stopped

To make it clear, consider the following example:

$months = array('January', 'February');
$each1 = each($months);
$each2 = each($months);
$each3 = each($months);

echo '<pre>'; 
    [1] => January
    [value] => February
    [0] => 0
    [key] => 0
    [1] => February
    [value] => February
    [0] => 1
    [key] => 1


The above example shows that the $each3 variable has an empty value that is FALSE.

VI. Do While In PHP

Honestly, I rarely (or probably never) use this loop, this is because (I think) require slightly different logic from the other loop, however, we still need to know this loop.

Same as while loop, do while is also be used when we do not know the end of the loop, the difference is at least the statement will be executed once.

The writing rule of do while in PHP

The do while loop has the following writing rule:

do {
	statement; // executed first
} while (expression); // evaluated after statement executed

When do we use the do while loop?

Some people are wondering, in the real world, on what conditions does the do while loop is needed? this, of course, depends on the case faced by each people.

We have our own coding style and habit, and the do while loop can be easily replaced with another loop that we comfortable with, hence this is why this loop is rarely used.

But anyway, for the real-world use, I’ll try to give an example here. Back to the previous example, we’ll cut a text/sentence at the particular number of letter (though actually using while loop is enough and easier to understand)

$max_char	= 45;
$text 		= 'This is an example of quite long text or sentence and we want to cut it to use as an excerp';

do {
	$char  = $text{--$max_char};
} while ($char != ' ');

echo substr($text, 0, $max_char) . '...';

The Result: This is an example of quite long text or…

From the example above, at least the statement ( $char = $text{--$max_char} ) will be executed once, after that, the expression ( $char != ' ' ) will be evaluated whether the value of $char variable is space, if FALSE then the loop will be executed again and again until the $char variable has value of space character (‘ ‘).


Both while and do while loop is used when we do not know the number of the loops or do not want to write down the number of loop on expression.

But there is once differences that is in the do while loop, the expression is checked at the end of the loop so that at least the statement will be executed once.

Related Post

Leave a comment

Like Us