Looping in PHP
1.
Initialization
2.
Termination
3.
Loop code
block
4.
Loop
processing
Types of
loops:-
- while - loops
- do...while - loops
- for - loops
- foreach -
PHP while Loop
The while
loop executes a block of code as long
as the specified condition is true.
Syntax
while (condition is true)
{ code to be
executed; }
Examples
The example below displays the numbers from 1
to 5:
Example
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x
<br>";
$x++;
}
?>
Example:-
<?php
$x = 0;
while($x <= 100)
{
echo "The number is: $x <br>";
$x+=10;
}
?>
====================================================================
PHP do while Loop
The do...while
loop will always execute the block of
code once, it will then check the condition, and repeat the loop while the
specified condition is true.
Syntax
do {
code to be executed;
} while (condition is true);
example:-
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x
<= 5);
?>
Note: In
a do...while
loop the condition
is tested AFTER executing the statements within the loop. This means that
the do...while
loop will execute
its statements at least once, even if the condition is false.
Example:-
<?php
$x = 6;
do {
echo "The number is: $x <br>";
$x++;
} while ($x
<= 5);
?>
====================================================================
PHP for Loop
The for
loop is used when we know in advance
how many times the script should run. it is
the most complex
loops in PHP. They behave like C- language like.
Syntax:-
- expr1: conditionally for the beginning of the loop.
- expr2:
loop ends condition. If it evaluates to
TRUE
, the loop continues and the nested statement(s) are executed. If it evaluates toFALSE
, the execution of the loop ends. - expr3: loop processing ex. Increment or decrement is executed.
- Each of the expressions can be empty or
contain multiple expressions separated by commas. In expr2,
all expressions separated by a comma are evaluated but the result is taken from
the last part. expr2 being empty means the loop should
be run indefinitely (PHP implicitly considers it as
TRUE
, like C).
for
(initialized counter; test counter;
increment counter)
{
code to be executed for each iteration;
}
examples:- WAP to display the numbers 1 through 10:
<?php
/* example 1 */
for ($i = 1; $i <= 10; $i++) {
echo $i;
}
/* example 2 */
for ($i = 1; ; $i++) {
if ($i > 10) {
break;
}
echo $i;
}
/* example 3 */
$i = 1;
for (; ; ) {
if ($i > 10) {
break;
}
echo $i;
$i++;
}
/* example 4 */
for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);
?>
Note:- first
example is to be the nicest one but we are able to use empty expressions
in for
loops
on many occasions.
PHP also supports the alternate "colon syntax"
for for
loops.
for (expr1; expr2; expr3):
statement
...
endfor;
=====================
PHP foreach Loop
The foreach
provides an
easy way to iterate over arrays.
it
works
only on arrays and objects, and will show an error when trying to use it on a
variable with a different data type or an uninitialized variable.
There are two syntaxes:
foreach (iterable_expression as $value)
statement
or
foreach (iterable_expression as $key => $value)
statement
The first form traverses the loop given by loop expression
.
On each iteration, the value of the current element is assigned to $value
.
The second form will additionally assign the current
element's key to the $key
variable on each iteration.
It is possible to customize object iteration.
$value
with &. In
that case, the value will be assigned by reference.Examples
The following example will output the values
of the given array ($colors):
Example
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value
<br>";
}
?>
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach($age as $x => $val) {
echo "$x =
$val<br>";
}
?>
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?>
Note:
foreach
does
not support to suppress error messages using @
.
Some more examples to demonstrate usage:
<?php
/* foreach example 1: value only */
$a = array(1, 2, 3, 17);
foreach ($a as $v) {
echo "Current value of \$a: $v.\n";
}
/* foreach example 2: value (with its manual access notation printed for illustration) */
$a = array(1, 2, 3, 17);
$i = 0; /* for illustrative purposes only */
foreach ($a as $v) {
echo "\$a[$i] => $v.\n";
$i++;
}
/* foreach example 3: key and value */
$a = array(
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => 17
);
foreach ($a as $k => $v) {
echo "\$a[$k] => $v.\n";
}
/* foreach example 4: multi-dimensional arrays */
$a = array();
$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";
foreach ($a as $v1) {
foreach ($v1 as $v2) {
echo "$v2\n";
}
}
/* foreach example 5: dynamic arrays */
foreach (array(1, 2, 3, 4, 5) as $v) {
echo "$v\n";
}
?>
====================================================================
PHP Break and Continue
PHP
Break
It was used to "jump out" of
a switch
statement.
The break
the statement
can also be used to jump out of a loop.
Syntax:-
break;
The PHP break keyword is used to terminate
the execution of a loop prematurely.
The break statement is situated inside the
statement block. After the break execution loop can come out. After coming out
of a loop immediate statement to the loop will be executed.
Example:
<?php |
$i = 0; |
while( $i < 5) |
{ |
$i++; |
if( $i == 2 )break; |
} |
echo (“Loop stopped at i = $i” ); |
?> |
Output:
Loop stopped at i = 2
This example jumps out of the loop when x is
equal to 4:
Example
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
break;
echo "The
inside if number is: $x <br>";
}
echo "The inside loop number
is: $x <br>";
}
echo "The
outside loop number is: $x <br>";
?>
PHP
Continue
The PHP continue keyword is used to halt the
current iteration of a loop but it does not terminate the loop.
Just like the break statement, the continue
statement is situated inside the statement block containing the code that the
loop executes, preceded by a conditional test. After continue statement
execution the rest of the loop code is
skipped and the next pass starts.
Example:
<?php |
$array = array( 1, 2, 3, 4, 5); |
foreach( $array as $value ) |
{ |
if( $value == 3
)continue; |
echo “Value is $value
<br />”; |
} |
?> |
Output:
Value is 1
Value is 2
Value is 4
Value is 5
This example skips the value of 4:
Example
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
continue;
}
echo "The number is: $x
<br>";
}
?>
Break and Continue in While Loop
We can also use break
and continue
in while
loops:
Break Example
<?php
$x = 0;
while($x < 10) {
if ($x == 4) {
break;
}
echo "The number is: $x
<br>";
$x++;
}
?>
Continue
Example
<?php
$x = 0;
while($x < 10) {
if ($x == 4) {
$x++;
continue;
}
echo "The number is: $x
<br>";
$x++;
}
?>
Example:-
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value ) {
if( $value == 3 )continue;
echo "Value is $value <br
/>";
}
?>
</body>
</html>
This will produce the following result −
Value is 1
Value is 2
Value is 4
Value is 5
Example:-
<?php
/*PHP program to print the
number pyramid of height n(input from user) using a single variable in entire
program
for 3
1
11
111
Input
enter pyramid height:5
Output
1
11
111
1111
11111
*/
for($i=0;$i<5;$i++)
{
$p=(10**($i+1)-1)/9;
echo "<br>";
echo($p);
}
?>
Nested loop
A loop within a
loop.
Syntax :-
for (expr1; expr2; expr3) {
for (expr1; expr2; expr3) {
//statement;
}
}
Ex.
<?php
for ($i = 1; $i < 5; $i++) {
for ($j = 1; $j <= $i; $j++)
{
echo " *
";
}
echo '<br />';
}
?>
Output:-
*
* *
* * *
* * * *
Ex.
<?php
for ($i = 1; $i < 5; $i++) {
for ($j = $i; $j < 5; $j++)
{
echo " *
";
}
echo '<br />';
}
?>
Output: -
* * * *
* * *
* *
*
Ex.
<?php
for ($i = 1; $i < 5; $i++) {
for ($j = $i; $j <= 5; $j++)
{
echo
" "; // it will print blank space
}
for ($j = 1; $j <= $i; $j++)
{
echo " *
";
}
echo '<br />';
}
?>
Output
*
* *
* * *
* * * *
0 Comments