PHP loops

Lecture



In second place in terms of frequency of use, after the construction of conditions (conditional operators), are cycles .

Loops allow you to repeat a certain (and even indefinite - when the work of the cycle depends on the condition) the number of times different operators. These operators are called body cycle . The loop pass is called iteration .

PHP supports three kinds of loops:

  • Cycle with precondition ( while );
  • Cycle with postcondition ( do-while );
  • Loop with counter ( for );
  • A special loop to iterate over arrays ( foreach ).

When using cycles, it is possible to use the break and continue statements . The first of them interrupts the work of the entire cycle, and the second - only the current iteration.

Consider PHP loops:

While precondition loop

A loop with a while precondition works according to the following principles:

  1. The value of the logical expression is calculated.
  2. If the value is true, the loop body is executed; otherwise, we move to the next statement after the loop.

Cycle syntax with precondition:

while (логическое_выражение)
инструкция;

In this case, the loop body is instruction . Usually the cycle body consists of a large number of statements. Here is an example of a loop with a while precondition:

<? php
$ x = 0 ;
while   ($ x ++< 10 ) echo $ x ;
// Выводит 12345678910
?>

Pay attention to the sequence of operations of the condition $ x ++ <10 . First, the condition is checked, and only then the value of the variable increases. If we set the increment operation before the variable ( ++ $ x <10 ), then the variable will be incremented first, and then the comparison will be performed. As a result, we get the line 123456789 . The same cycle could be written differently:

<? php
$ x = 0 ;
while   ($ x < 10 )
{
$ x ++;   // Увеличение счетчика
echo $ x ;
}
// Выводит 12345678910
?>

If we increase the counter after the echo statement, we get the line 0123456789 . In any case, we have 10 iterations. Iteration is the execution of statements inside the loop body.

Similar to the conditional if statement , you can group statements within the body of a while loop using the following alternative syntax:

while ( логическое_выражение ):
инструкция;
...
endwhile;

An example of using alternative syntax:

<?php
$x = 1;
while ($x <= 10):
echo $x;
$x++;
endwhile;
?>

Do while post-conditional loop

Unlike the while loop , this loop checks the value of the expression not before , but after each pass (iteration). Thus, the loop body is executed at least once. The loop syntax with a postcondition is as follows:

do
{
тело_цикла;
}
while (логическое_выражение);

After the next iteration, it is checked whether the logical_expression is true, and, if so, control is transferred again to the beginning of the cycle, otherwise the cycle is terminated.
PHP developers did not provide an alternative syntax for the do-while (apparently due to the fact that, unlike application programming, this cycle is quite rarely used when programming web applications).

An example of a script showing the operation of a loop with a do-while postcondition:

<?php
$x = 1;
do {
echo $x;
} while ($x++<10);
?>

The reviewed script prints: 12345678910

Loop with for counter

A loop with a counter is used to perform a loop body a certain number of times. Using the for loop, you can (and need) create constructs that will perform actions that are not at all as trivial as a simple reassembly of the counter value.

The for loop syntax is:

for (инициализирующие_команды; условие_цикла; команды_после_итерации) { тело_цикла; }

The for loop starts with executing initialisation_commands. These commands are executed only once. After this, the loop condition is checked, if it is true ( true ), then the body loop is executed. After the last statement of the body is executed, the after_ite commands are executed. Then the loop condition is checked again. If it is true ( true ), the body of the loop and the commands of the after iteration are executed, and so on.

<? php
for   ($ x = 0 ;   $ x < 10 ;   $ x ++) echo $ x ;
?>

This script displays: 0123456789

There is an option to output the line 12345678910 :

<? php
for   ($ x = 0 ;   $ x ++< 10 ;) echo $ x ;
// Выводит 12345678910
?>

In this example, we have provided an increase in the counter when checking a logical expression. In this case, we did not need commands that were executed after the iteration.

If you need to specify multiple commands, they can be separated by commas, for example:

<? php
for   ($ x = 0 ,   $ y = 0 ;   $ x < 10 ;   $ x ++,   $ y ++) echo $ x ;
// Выводит 0123456789
?>

Here is another, more practical example of using several commands in a for loop:

<? php
for($ i = 0 ,$ j = 0 ,$ k = "Точки" ;   $ i < 10 ;   $ j ++,$ i +=$ j )   {   $ k =$ k . "." ; echo $ k ;   }
// Выводит Точки.Точки..Точки...Точки....
?>

The considered example (and indeed any for loop) can be implemented through the while , only it will not look so elegant and concise.

There is an alternative syntax for the for loop:

for(инициализирующие_команды; условие_цикла; команды_после_итерации):
операторы;
endfor;

Loop looping foreach arrays

In PHP4, another special type of loop appeared - foreach . This cycle is designed specifically for iterate through arrays .

The foreach loop syntax is as follows:

foreach (массив as $ключ=>$значение)
команды;

Here, the commands are executed cyclically for each element of the array, and the next key pair => value is in the variables $ key and $ value . Here is an example of the foreach loop operation:

<? php
$ names [ "Иванов" ]   =   "Андрей" ;
$ names [ "Петров" ]   =   "Борис" ;
$ names [ "Волков" ]   =   "Сергей" ;
$ names [ "Макаров" ]   =   "Федор" ;
foreach ($ names as $ key =>   $ value )   {
echo "<b>$value $key</b><br>" ;
}
?>

The reviewed script displays:

Андрей Иванов
Борис Петров
Сергей Волков
Федор Макаров

The foreach loop has another form of record that should be used when we are not interested in the value of the key of the next element. It looks like this:

foreach (массив as $значение)
команды;

In this case, only available value of the next element of the array, but not its key. This can be useful, for example, for working with list arrays:

<? php
$ names []   =   "Андрей" ;
$ names []   =   "Борис" ;
$ names []   =   "Сергей" ;
$ names []   =   "Федор" ;
foreach ($ names as $ value )   {
echo "<b>$value</b><br>" ;
}
?>

Attention: The foreach loop operates not with the original array, but with its copy. This means that any changes that are made to the array cannot be "visible" from the loop body. That allows, for example, to use not only a variable as an array, but also the result of some function returning an array (in this case, the function will be called only once - before the cycle begins, and then the work will be done with a copy of the returned value).

Break construction

Very often, in order to simplify the logic of a complex cycle, it is convenient to be able to interrupt it in the course of the next iteration (for example, when performing some special condition). For this, there is a break construct that provides an immediate exit from the loop. It can be specified with one optional parameter — a number that indicates from which nested loop the output should be made. The default is 1 , that is, the output from the current loop, but sometimes other values ​​are used. Break construction syntax:

break; // По умолчанию
break(номер_цикла); // Для вложенных циклов (указывается номер прерываемого цикла)

Here are some examples:

<? php
$ x = 0 ;
while   ($ x ++< 10 )   {
if   ($ x == 3 )   break;
echo "<b>Итерация $x</b><br>" ;
}
// Когда $x равен 3, цикл прерывается
?>

The reviewed script displays:

Итерация 1
Итерация 2

If we need to interrupt the work of a certain (nested) cycle, then we need to pass the constructions break parameter - cycle number , for example, break (1) . The numbering of the cycles is as follows:

for (...) // Третий цикл
{
for (...) // Второй цикл
{
for (...) // Первый цикл
{
}
}
}

Construction continue

The construction of continue , like break , works only "in a pair" with cyclic constructions. It immediately ends the current iteration of the loop and proceeds to a new one (of course, if the loop condition for the loop with the precondition is satisfied). In the same way as for break , for continue you can specify the nesting level of the loop, which will be continued upon return of control.
Basically, continue allows you to save the number of curly braces in the code and increase its readability. This is most often needed in filter loops, when you need to loop through a certain number of objects and select from them only those that satisfy certain conditions. Let's give an example of using the continue construction:

<? php
$ x = 0 ;
while   ($ x ++< 5 )   {
if   ($ x == 3 )   continue;
echo "<b>Итерация $x</b><br>" ;
}
// Цикл прервется только на третьей итерации
?>

This script displays:

Итерация 1
Итерация 2
Итерация 4
Итерация 5

Proper use of break and continue allows to significantly improve the "readability" of the code and the number of else blocks.

created: 2016-01-25
updated: 2021-03-13
132487



Rating 8 of 10. count vote: 6
Are you satisfied?:



Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Running server side scripts using PHP as an example (LAMP)

Terms: Running server side scripts using PHP as an example (LAMP)