Blog de programación, errores, soluciones

Chose Language:
Author: Admin/Publisher |finished | checked

PHP while and do-while statements

One of the simplest ways PHP has to create a loop or repeat a block of code while a condition is met is while, and we can also use do-while to go through the block at least once.

It was decided to make this new section separate from control structures, for these blocks due to public demand. This way, we can better explain and give more examples. Thanks for understanding.


In the while statement, if the expression is true, the block within while will repeat until it is false. We have to be careful here, because if the expression is always true, it will create an infinite loop.

Sintaxis / Sintax
   //bloque a ejecutar

We can also express while in the following way. This is an alternative way of writing this control structure.

Sintaxis / Sintax
 //bloque a ejecutar

Example of while:

Ejemplo de while
$a = 7;
   echo $a;
}//repetira esto hasta llegar a 2
echo "termino el loop";

The most common use of while is data reading, especially data coming from a query to the database. This can also be done using foreach because we can tell the MySQLi extension how we want to retrieve the data.

In terms of preference, I like to use foreach, but in the professional field while is probably preferred. Anyway, remember that this depends on what we specify in the MySQLi extension or the PDO extension.

In a while loop, it would be something like this:

while ($fila = mysqli_fetch_array($result)){
   // codigo que mostrara los datos

On the other hand, in foreach, we will get all the data from the query and iterate over them.

PHP do-while

The do-while statement is similar to while except that in the do-while statement the block executes at least once. The block is executed and then the expression is checked; if it’s true, the block continues to execute.

Sintaxis / Sintax
  //bloque a ejecutar

Example in which the block is executed once:

$a = 0;
   echo "recorro el bloque al menos 1 vez";

At times, it might be necessary to use do-while, for example in a crawler to read a page, since obtaining the links will be done at least once. Another option is data reading.

You can see a less detailed form of control structures here: [ES]

Category: en-php
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category