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.
The principle is the same for all programming languages. Since you chose PHP, I recommend studying the basics in C first.
– Ericson Willians
I chose php because it is the language I most use, and so the question is not too wide. I appreciate the recommendation.
– Florida
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).
– Ericson Willians