- PHP Loop: For, ForEach, While, Do While [Example]
- PHP For Loop
- PHP For Each loop
- While Loop
- PHP While loop
- PHP Do While
- Summary
- do-while
- Do while examples in php
- User Contributed Notes 6 notes
- Использование циклов в PHP
- Foreach – перебор массива
- Результат:
- Альтернативный синтаксис foreach
- For – цикл с счетчиком
- Результат:
- Альтернативный синтаксис
- Результат:
- Альтернативный синтаксис for
- While – цикл с предусловием
- Результат:
- Альтернативный синтаксис while
- Do-while – цикл с постусловием
- Результат:
- Управление циклами
- Break
- Continue
- Результат:
PHP Loop: For, ForEach, While, Do While [Example]
A Loop is an Iterative Control Structure that involves executing the same number of code a number of times until a certain condition is met.
PHP For Loop
The above code outputs “21 is greater than 7” For loops For… loops execute the block of code a specifiednumber of times. There are basically two types of for loops;
Let’s now look at them separately. For loop It has the following basic syntax
- “for…” is the loop block
- “initialize” usually an integer; it is used to set the counter’s initial value.
- “condition” the condition that is evaluated for each php execution. If it evaluates to true, then execution of the for… loop continues. If it evaluates to false, the execution of the for… loop is terminated.
- “increment” is used to increment the initial value of counter integer.
How it works
The flowchart shown below illustrates how for loop in php works
How to code
The code below uses the “for… loop” to print values of multiplying 10 by 0 through to 10
The product of 10 x 0 is 0 The product of 10 x 1 is 10 The product of 10 x 2 is 20 The product of 10 x 3 is 30 The product of 10 x 4 is 40 The product of 10 x 5 is 50 The product of 10 x 6 is 60 The product of 10 x 7 is 70 The product of 10 x 8 is 80 The product of 10 x 9 is 90
PHP For Each loop
The php foreach loop is used to iterate through array values. It has the following basic syntax
- “foreach(…)” is the foreach php loop block code
- “$array_data” is the array variable to be looped through
- “$array_value “ is the temporary variable that holds the current array item values.
- “block of code…” is the piece of code that operates on the array values
How it works The flowchart shown below illustrates how the for… each… loop works
Practical examples
The code below uses for… each loop to read and print the elements of an array.
Lion Wolf Dog Leopard Tiger
Let’s look at another example that loops through an associative array.
An associative array uses alphanumeric words for access keys.
"Female", "John" => "Male", "Mirriam" => "Female"); foreach($persons as $key => $value)< echo "$key is $value"."
"; > ?>
The names have been used as array keys and gender as the values.
Mary is Female John is Male Mirriam is Female
While Loop
PHP While loop
They are used to execute a block of code a repeatedly until the set condition gets satisfied
When to use while loops
- While loops are used to execute a block of code until a certain condition becomes true.
- You can use a while loop to read records returned from a database query.
Types of while loops
- Do… while – executes the block of code at least once before evaluating the condition
- While… – checks the condition first. If it evaluates to true, the block of code is executed as long as the condition is true. If it evaluates to false, the execution of the while loop is terminated.
It has the following syntax
- “while(…)” is the while loop block code
- “condition” is the condition to be evaluated by the while loop
- “block of code…” is the code to be executed if the condition gets satisfied
How it works
The flow chart shown below illustrates how the while… loop works
Practical example
The code below uses the while… loop to print numbers 1 to 5.
PHP Do While
The difference between While… loop and Do… while loop is do… while is executed at-least once before the condition is evaluated.
Let’s now look at the basic syntax of a do… while loop
- “do while(…)” is the do… while loop block code
- “condition” is the condition to be evaluated by the while loop
- “block of code…” is the code that is executed at least once by the do… while loop
How it works
The flow chart shown below illustrates how the while… loop works
Practical example
We are now going to modify the while… loop example and implement it using the do… while loop and set the counter initial value to 9.
The code below implements the above modified example
The above code outputs:
Note the above example outputs 9 only.
This is because the do… while loop is executed at least once even if the set condition evaluates to false.
Summary
- The for… loop is used to execute a block of a specified number of times
- The foreach… loop is used to loop through arrays
- While… loop is used to execute a block of code as long as the set condition is made to be false
- The do… while loop is used to execute the block of code at least once then the rest of the execution is dependent on the evaluation of the set condition
do-while
Цикл do-while очень похож на цикл while, с тем отличием, что истинность выражения проверяется в конце итерации, а не в начале. Главное отличие от обычного цикла while в том, что первая итерация цикла do-while гарантированно выполнится (истинность выражения проверяется в конце итерации), тогда как она может не выполниться в обычном цикле while (истинность выражения которого проверяется в начале выполнения каждой итерации, и если изначально имеет значение FALSE , то выполнение цикла будет прервано сразу).
Есть только один вариант синтаксиса цикла do-while:
В примере цикл будет выполнен ровно один раз, так как после первой итерации, когда проверяется истинность выражения, она будет вычислена как FALSE ( $i не больше 0) и выполнение цикла прекратится.
Опытные пользователи С могут быть знакомы с другим использованием цикла do-while, которое позволяет остановить выполнение хода программы в середине блока, для этого нужно обернуть нужный блок кода вызовом do-while (0) и использовать break. Следующий фрагмент кода демонстрирует этот подход:
do if ( $i < 5 ) echo "i еще недостаточно велико" ;
break;
>
$i *= $factor ;
if ( $i < $minimum_limit ) break;
>
echo «значение i уже подходит» ;
?php
Не беспокойтесь, если вы не понимаете это сразу или вообще. Вы можете писать скрипты и даже мощные программы без использования этой ‘возможности’. Начиная с версии PHP 5.3.0, стало возможным использовать оператор goto вместо подобного «хака».
Do while examples in php
do-while loops are very similar to while loops, except the truth expression is checked at the end of each iteration instead of in the beginning. The main difference from regular while loops is that the first iteration of a do-while loop is guaranteed to run (the truth expression is only checked at the end of the iteration), whereas it may not necessarily run with a regular while loop (the truth expression is checked at the beginning of each iteration, if it evaluates to false right from the beginning, the loop execution would end immediately).
There is just one syntax for do-while loops:
The above loop would run one time exactly, since after the first iteration, when truth expression is checked, it evaluates to false ( $i is not bigger than 0) and the loop execution ends.
Advanced C users may be familiar with a different usage of the do-while loop, to allow stopping execution in the middle of code blocks, by encapsulating them with do-while (0), and using the break statement. The following code fragment demonstrates this:
It is possible to use the goto operator instead of this hack.
User Contributed Notes 6 notes
There is one major difference you should be aware of when using the do—while loop vs. using a simple while loop: And that is when the check condition is made.
In a do—while loop, the test condition evaluation is at the end of the loop. This means that the code inside of the loop will iterate once through before the condition is ever evaluated. This is ideal for tasks that need to execute once before a test is made to continue, such as test that is dependant upon the results of the loop.
Conversely, a plain while loop evaluates the test condition at the begining of the loop before any execution in the loop block is ever made. If for some reason your test condition evaluates to false at the very start of the loop, none of the code inside your loop will be executed.
The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop will write some output, and then increment the variable $x with 1. Then the condition is checked (is $x less than, or equal to 5?), and the loop will continue to run as long as $x is less than, or equal to 5:
Do-while loops can also be used inside other loops, for example:
// generating an array with random even numbers between 1 and 1000
$numbers = array();
$array_size = 10 ;
// for loop runs as long as 2nd condition evaluates to true
for ( $i = 0 ; $i < $array_size ; $i ++)
// always executes (as long as the for-loop runs)
do <
$random = rand ( 1 , 1000 );
// if the random number is even (condition below is false), the do-while-loop execution ends
// if it’s uneven (condition below is true), the loop continues by generating a new random number
> while (( $random % 2 ) == 1 );
// even random number is written to array and for-loop continues iteration until original condition is met
$numbers [] = $random ;
>
// sorting array by alphabet
echo ‘
' ;
print_r ( $numbers );
echo '
‘ ;
?>
I’m guilty of writing constructs without curly braces sometimes. writing the do—while seemed a bit odd without the curly braces (< and >), but just so everyone is aware of how this is written with a do—while.
a normal while:
while ( $isValid ) $isValid = doSomething ( $input );
?>
a do—while:
do $isValid = doSomething ( $input );
while ( $isValid );
?>
Also, a practical example of when to use a do—while when a simple while just won’t do (lol). copying multiple 2nd level nodes from one document to another using the DOM XML extension
# open up/create the documents and grab the root element
$fileDoc = domxml_open_file ( ‘example.xml’ ); // existing xml we want to copy
$fileRoot = $fileDoc -> document_element ();
$newDoc = domxml_new_doc ( ‘1.0’ ); // new document we want to copy to
$newRoot = $newDoc -> create_element ( ‘rootnode’ );
$newRoot = $newDoc -> append_child ( $newRoot ); // this is the node we want to copy to
# loop through nodes and clone (using deep)
$child = $fileRoot -> first_child (); // first_child must be called once and can only be called once
do $newRoot -> append_child ( $child -> clone_node ( true )); // do first, so that the result from first_child is appended
while ( $child = $child -> next_sibling () ); // we have to use next_sibling for everything after first_child
?>
If you put multiple conditions in the while check, a do-while loop checks these conditions in order and runs again once it encounters a condition that returns true. This can be helpful to know when troubleshooting why a do-while loop isn’t finishing. An (illustrative-only) example:
$numberOne = 0 ;
do echo $numberOne ;
$numberOne ++;
> while( $numberOne < 5 || incrementNumberTwo () );
function incrementNumberTwo () echo «function incrementNumberTwo called» ;
return false ;
>
// outputs «01234function incrementNumberTwo called»
?>
Использование циклов в PHP
PHP имеет четыре вида циклов и операторы управления ими, рассмотрим поподробнее.
Foreach – перебор массива
Предназначен для перебора элементов массива.
$array = array( 1 => 'Значение 1', 2 => 'Значение 2', 3 => 'Значение 3', 4 => 'Значение 4', ); // Вывод ключей foreach ($array as $key => $val) < echo $key . '
'; > // Вывод значений foreach ($array as $key => $val) < echo $val . '
'; >
Результат:
1 2 3 4 Значение 1 Значение 2 Значение 3 Значение 4
Альтернативный синтаксис foreach
For – цикл с счетчиком
Цикл работает пока выполняется заданное условие. Обычно применяется в качестве счетчика.
// Счетчик от 0 до 5 for ($n = 0; $n // Счетчик от 5 до 0 for ($n = 5; $n >= 0; $n--)
Результат:
Альтернативный синтаксис
$array = array( 'Значение 1', 'Значение 2', 'Значение 3', 'Значение 4', ); for ($n = 0; $n < count($array); $n++) < echo $array[$n] . '
'; >
Результат:
Значение 1 Значение 2 Значение 3 Значение 4
Альтернативный синтаксис for
While – цикл с предусловием
Т.е. если перед началом итерации условие выполняется, то цикл продолжает свою работу.
Результат:
Альтернативный синтаксис while
Do-while – цикл с постусловием
В отличии от while этот цикл проверяет выполнения условия после каждой итерации. Do-while не имеет альтернативного синтаксиса.
Результат:
Управление циклами
Break
Вызов break или break 1 в цикле останавливает его.
Для вложенных циклов используется break 2 и т.д.
Continue
Используется для пропуска итерации.
Результат:
Для вложенных циклов по аналогии с break 2 , break 3 – continue 2 , continue 3 .