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.

while

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
while($expresion){
   //bloque a ejecutar
}

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

Sintaxis / Sintax
while($expresion):
 //bloque a ejecutar
endwhile;

Example of while:

Ejemplo de while
<?php
$a = 7;
while($a>1){
   echo $a;
   $a=$a-1;
}//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
do{
  //bloque a ejecutar
}while(expresion);

Example in which the block is executed once:

Ejemplo
<?php
$a = 0;
do{
   echo "recorro el bloque al menos 1 vez";
   $a=$a-1;
 }while(7<$a);
?>

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]https://blastcoding.com/estructuras-de-control-php/

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