What is the difference between while, for, while and foreach?

Asked

Viewed 19,255 times

14

What is the difference between the while , do while, for and foreach in PHP, because they give the impression that same functionality.

All of them can be used to create a loop or has other purposes?

What a simple example of each person’s use would look like?

  • 1

    The principle is the same for all programming languages. Since you chose PHP, I recommend studying the basics in C first.

  • I chose php because it is the language I most use, and so the question is not too wide. I appreciate the recommendation.

  • All of them sane loops (flow control instructions). For-each is the most extravagant, as it is specific to scrolling through collections (Abstractions of high-level languages such as Python, JS, PHP, Ruby and other derivatives of C), but it is also a loop. Everything you do with a do-while, for and for-each you can do with a simple while. When translating to Assembly, everyone boils down to the JMP instruction (Jump).

3 answers

28


They are all used for loops. There are even some "creative" uses, but they will always be controlled repetitions.

while

The structure of flow control enquanto repeats the command block until the established condition is false. The block may never perform since the condition is earlier, and at that specific point is like a if, where it enters the block only if the condition is true, the difference to the if is that at the end of the block he returns to the beginning to test the condition again, and does not have a else, at least in PHP.

It is used in situations you don’t know the beginning and end of anything, something you have little control of what will determine until you repeat.

while ($row = mysqli_fetch_assoc($result)) {
    $html .= $row;
}

do...while

It’s basically the same thing as while, but the condition is at the end, so it is guaranteed that the block will perform at least once.

do {
    //executa algo
} ($condicao);

It would be the same as doing:

while (true) {
    //executa algo
    if (!$condicao) {
        break;
    }
}

for

It’s like the while, but it is an even more structured way where an advance action is applied at the end of every iteration. In general it is used to go from one point to another where you know the beginning and the end, in addition to having an advance instruction in each step.

In addition to the condition there are two other information in its construction:

  • one that initializes some variable or possibly performs some action within the scope of the block, this runs only once

  • another that runs every time it finishes a pass in the block and doesn’t come out of it forcibly. The most common is to make some arithmetic or geometric increment or decrement, but it can be used for other operations, including only calling some function that needs a guarantee that will always be executed in each repetition. Example:

    for ($i = 0; $i < 10; $i++)
    

describing:

for ($i = 0; // inicialização, executa apenas uma vez
     $i < 10; //condição é avaliada em cada passo da repetição, antes de iniciar o bloco
     $i++) //execução de passo

Note that the step to be executed will even occur if a command continue is applied within the loop. Some people think that the for is the same as:

$i = 0;
while ($i < 10) {
    //executa algo
    i++;
}

As long as you don’t have one continue inside the loop. This is already different:

$i = 0;
while ($i < 10) {
    //executa algo
    if (alguma condição) {
        continue; //o incremento não será executado, no for seria
    }
    i++;
}

There is also another difference that the variable $i is outside the scope of the loop. This may be desirable, but the for can be done too, just have the boot done out. If it is in the block scope this variable cannot be used after it has finished running.

All 3 elements of the for are optional. You do not need to initialize anything if you have nothing useful to do. You do not need to have the step, which indicates that maybe the while is more suitable in many situations like this. Nor does the condition need to be executed, which is rare but useful. Some people like to use a building for to establish a loop infinite, which obviously needs to have something internal that determines its end:

for (;;) { //faz algo aqui e deve ter um if com break }

These are the main reasons to prefer it. But people also use it because it saves a line on that pattern compared to while.

It is possible to initialize and "increment" more than one variable at the same time. Example:

for ($x = 1, $y = 1; $x <= 10; $x++, $y++) {
    if (($y % 2) == 0) {
        $impar += $y;
    }
    $total += $x;
}

The condition should be unique since it has to result in a unique boolean. Of course you can use relational operators like || and &&, as in any conditional expression, it is thus possible to compare the two variables or other relevant elements.

foreach

It is a controlled repeat from start to finish with a specific pattern in data collections.

There is no condition, it scans a collection of data from start to finish (this collection may be a subset of a larger collection). Any data having multiple elements can be used, normally a array or string is the most common. It is less common, but it is possible to even iterate over an object and catch each class member.

It is a more controlled and abstract form of execution and avoids some problems that the most careless programmer (which is normal) may end up doing in more "free" repetitions. It is generally preferred when evaluating an entire data sequence.

It is possible to evaluate a fraction of the data collection through some function that provides different start and end than normal.

In some cases the for may be more suitable because it can better control how to interact and access the elements. By for you vary the index of access to the elements of the collection, foreach you receive the element itself. It can be done, but it’s a little more complicated to do right, perform counts (simple increments) on foreach.

Note that if you create your own data collection, you must meet certain requirements so that it works properly with the foreach who expects a pattern from these collections.

It should be preferred whenever it is the most appropriate. The for and especially the two outings of while should not be used in collections unless you need to do something out of the ordinary foreach takes good care.

$cores = array("azul", "amarelo", "verde", "vermelho");
foreach ($cores as $cor) {
    echo "$cor<br>";
}

It has function ready that does exactly that and some people prefer this even more abstract form, but not every problem is so simple.

This could be written with for, but it is not the most appropriate:

$cores = array("azul", "amarelo", "verde", "vermelho");
for ($i = 0; i < count($cores); i++) {
    echo "$cores[$i]<br>"; //note o índice sendo usado
}

Or it could be done with the while with the same result since it does not have a continue and the scope of $i is not important:

$cores = array("azul", "amarelo", "verde", "vermelho");
$i = 0;
while (i < count($cores)) {
    echo "$cores[$i]<br>";
    $i++;
}

I put in the Github for future reference.

The do...while it would already be too complicated to reproduce the same, but it is perfectly possible, as shown in the example at the beginning of this post, think of getting ugly and not bringing any advantage.

Completion

Try to use the best tool for each case. The one that gives more semantics than you want to do.

4

Answer:

All of them can be used to create a loop, however there are some patterns to use one or another command.

Patterns:

  1. If you need to iterate a list of objects, the most appropriate commands are the foreach and the for. If list objects have attributes it is more recommended to use the foreach because you only have to worry about iterating the list without having a control variable as is the case for the variable $i which we will see in examples below.

  2. In other situations, for example if only one variable needs to be treated, and NAY a list of objects and commands while and do while would be better applied in this situation.

While: In English means While if a certain expression is true the loop continues, otherwise it exits the loop.

Example:

<?php
    $i = 0;
    while ($i != 10){
        $i = $i + 1;
        echo $i;
    } 
     echo "Fim de execução";
?>

When the variable $i is equal to 10 resulting in falso within the while the loop will be closed because 10 is equal to 10 and no different.

Do While: Compared to command While mentioned above, what is inside the command Do While will always be executed at least once, because the check whether or not to continue iterating is below. Note that in the example above, if the variable $i initialized with the value 10 would not enter into the loop.

Example:

<?php

    $i = -1;

    do {   

        echo $i;
        $i++;

    while ($i != 0);    
?>

The above command will be executed only once, because the variable $i was instantiated with the value -1 and within the iteration I make it increment 1 more, becoming 0, and when I fall in command while just below the variable $i will not be different from 0, coming out of the loop.

For: The syntax is different from the commands mentioned above, usually used when it is necessary to traverse a Array, because a variable that contains a Array has a number of elements inside.

Example:

<?php

     // Array com 3 (três) elementos
     $cachorros = Array("Pastor Alemão", "Cocker Spaniel", "Pitbull");

     $tamanho_array = count($cachorros);
     for ($i=0; $i < $tamanho_array; $i++){
          echo $cachorros[$i]."<br>";
     }
?>

In the example above I created a variable with a list of dog breeds, I saved it in the variable $tamanho_array the number of elements you have within the list, that is, the number of races you have within the array and using the command for I went through this list always incrementing the value of $i and the value of $i is equal to the number of breeds you have inside the quit loop list.

Foreach: Similar to the command for, however we do not need to increment a variable as is the case of $i, will usually be used to go through a list that can come from the database, works only with lists and objects.

<?php

     $pessoas = // Recebe uma lista de pessoas do banco de dados.

     foreach($pessoas as $pessoa){
          echo "Nome: ".$pessoa->getNome()."<br>";
          echo "Sexo: ".$pessoa->getSexo()."<br>";
     }

?>

The above command will exit the loop when the command foreach scroll through all elements of the list.

References:

PHP Manual - While

PHP Manual - Do While

PHP Manual - For

PHP Manual - Foreach

3

They all really have the same functionality with minor differences.

While: Runs the loop while the condition is true.

// Contar de 1 até 10
$contar = 1;
while($contar <= 10){
   echo "$contar";
   $contar++;
}

Do While: Runs the loop first and then checks the condition.

// Contar de 1 até 10
$contar = 0;
do{
    $contar++;
    echo "$contar";
}while($contar <= 10)

For: Runs the loop while the condition is true, but you can instantiate the counter variables within the loop structure.

for($contar = 1; $contar <= 10; $contar++){
    echo "$contar";
}

Foreach: Loops over elements of an array.

$contar = range(1, 10);
foreach($contar as $valor){
    echo "$valor";
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.