Loops in PHP

Loops in PHP

Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal code-lines in a script, we can use loops to perform a task like this.

In PHP, we have the following looping statements:

  • while - loops through a block of code as long as the specified condition is true
  • do...while - loops through a block of code once, and then repeats the loop as long as the specified condition is true
  • for - loops through a block of code a specified number of times
  • foreach - loops through a block of code for each element in an array

Break Statement

Break ends execution of the current for, foreach, while, do..while or switch structure. Break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of.

PHP Example:-

<?php
echo "<p><b>Example of using the Break statement:</b></p>";
for ($i=0; $i<=10; $i++)
{
if ($i==3)
{
break;
}
echo "The number is ".$i;
echo "<br />";
}
?>

Continue Statement

Continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the beginning of the next iteration.

Continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of.

PHP Example:-

<?php
echo "<p><b>Example of using the Continue statement:</b><p>";
for ($i=0; $i<=10; $i++)
{
if ($i==3)
{
continue;
}
echo "The number is ".$i;
echo "<br />";
}
?>

do while Statement

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's 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).

Syntax:-

do {
// code to be executed
} while ( expression );

PHP Example:- The code block is executed a minimum of one time.

<?php
$num = 1;
do {
echo"Execution number: $num<br>\n";
$num++;
} while ( $num > 200 && $num < 400 );
?>

The do...while statement tests whether the variable $num contains a value that is greater than 200 and less than 400. In line 7, we have initialized $num to 1, so this expression returns false. Nonetheless, the code block is executed before the expression is evaluated, so the statement will print a single line to the browser.

For Statement

For loops are the most complex loops in PHP. They behave like their C counterparts. The syntax of a for loop is:.

Syntax:-

for ( initialization expr1; test expr2; modification expr3 )
{ // code to be executed }

The first expression (expr1) is evaluated (executed) once unconditionally at the beginning of the loop.

In the beginning of each iteration, expr2 is evaluated. If it evaluates to TRUE, the loop continues and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends.At the end of each iteration, expr3 is evaluated (executed).

Each of the expressions can be empty. expr2 being empty means the loop should be run indefinitely (PHP implicitly considers it as TRUE, like C). This may not be as useless as you might think, since often you'd want to end the loop using a conditional break statement instead of using the for truth expression.

PHP Example:- All of them display numbers from 1 to 10:

<?php
for ($i = 1; $i <= 10; $i++) {
echo "$i\n";
}
for ($i = 1; ; $i++) {
if ($i > 10) {
break;
}
echo "$i\n";
}
?>

Foreach Statement

PHP 4 (not PHP 3) includes a foreach construct, much like Perl and some other languages. This simply gives an easy way to iterate over arrays. foreach works only on arrays, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes; the second is a minor but useful extension of the first:

Syntax:-

foreach (array_expression as $value) statement
foreach (array_expression as $key => $value) statement

The first form loops over the array given by array_expression. On each loop, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next loop, you'll be looking at the next element).

The second form does the same thing, except that the current element's key will be assigned to the variable $key on each loop.

While Statement

While loops are the simplest type of loop in PHP. They behave just like their C counterparts. The basic form of a while statement is:

Syntax:-

while ( expression ) {
// do something }

The meaning of a while statement is simple. It tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to TRUE. The value of the expression is checked each time at the beginning of the loop, so even if this value changes during the execution of the nested statement(s), execution will not stop until the end of the iteration (each time PHP runs the statements in the loop is one iteration). Sometimes, if the while expression evaluates to FALSE from the very beginning, the nested statement(s) won't even be run once.

PHP Example: The following code are identical, and both print numbers from 1 to 10:

<?php
$i = 1;
while ($i <= 10) {
echo "$i\n";
$i++;
}