PHP Loops
PHP Loops
Often when you write code, you want the same block
of code to run over and over again a certain number of
times. So, instead of adding several almost equal
code-lines in a script, we can use loops.
Syntax
for ( Initialization;
Condition; Increment/ Decrement
// Code to be executed
or oo
Tru e
loop
Example: Printing numbers from 1 to 5
using for loop.
PH p
1 <?php
2
3 // Code to
illustrate for loop
4 for ($num 1; $num
5; $num +=
5 echo $num
6
7
8
Output
12345
PHP while Loop
The while loop is also an entry control loop
like for loops. It first checks the condition
at the start of the loop and if its true then it
enters into the loop and executes the block
of statements, and goes on executing it as
long as the condition holds true.
Syntax
while ( condition ) {
// Codeis executed
hile loo
start
Test False
conditio
True
while loop en
Example: Printing numbers from 1 to 5.
1 <?php
2
3 $num
4
5 while ($num <=
6 echo $num
7 $num++;
8
9
10
Output
12345
PHP do-while Loop
The do-while loop is an exit control loop
which means, it first enters the loop,
executes the statements, and then checks
the condition. Therefore, a statement is
executed at least once using the do...while
loop. After executing once, the program is
executed as long as the condition holds
true.
Syntax
do {
// Codeis executed
} while ( condition ) ;
while loo
tart
Test False
conditio
True
while loop en
Example: Printing numbers from 1 to 5.
1 <?php
2
3 $num
4
5 do {
6 echo $num
7 $num++;
8 } while ($num <=
5);
9
10
Output
12345
PHP foreach Loop
This foreach loop is used to iterate over
arrays. For every counter of loop, an array
element is assigned and the next counter
is shifted to the next element.
Syntax:
// or
</body>
< / html >
red
green
blue
yellow