PHP Looping

PHP Looping

Loop: -repeating the same block of code to run over and over again a certain number of times as long as a certain condition is true. Entry-exit.

Elements of loops

  1. Initialization
  2. Termination
  3. Loop code block
  4. Loop processin 

Types of loops:-



  1. while - loops
  2. do...while - loops
  3. for - loops
  4. 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

Displays the numbers 1 to 5:

<?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

               for (expr1; expr2; expr3)
                 statement
  • expr1 is executed once unconditionally at the beginning of the loop.
  •  beginning of each iteration, expr2 is executed. 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 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;
}


Parameters:

  • init counter: Initialize the loop counter value
  • test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
  • increment counter: Increases the loop counter value


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 in many occasions.

PHP also supports the alternate "colon syntax" for for loops.

for (expr1; expr2; expr3):
    statement
   ...
endfor;

=======================================================================

PHP foreach Loop

The foreach construct provides an easy way to iterate over arrays. 

it works only on arrays and objects, and will issue an error when we try 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

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.

If we directly modify array elements within the loop then precede $value with &. In that case, the value will be assigned by reference.


Examples

wap for output the values of the given array ($colors):

<?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
?>


Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset() . Otherwise, we will experience the following behavior:

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
// without an unset($value), $value is still a reference to the last item: $arr[3]
foreach ($arr as $key => $value) {
    // $arr[3] will be updated with each value from $arr...
    echo "{$key} => {$value} ";
    print_r($arr);
}
// ...until ultimately the second-to-last value is copied onto the last value
// output:
// 0 => 2 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 2 )
// 1 => 4 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 4 )
// 2 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
// 3 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
?>

It is possible to iterate a constant array's value by reference:

<?php
foreach (array(1, 2, 3, 4) as &$value) {
    $value = $value * 2;
}
?>


Note:

foreach does not support the ability to suppress error messages using @.


Unpacking nested arrays with list()

It is possible to iterate over an array of arrays and unpack the nested array into loop variables by providing a list()  as the value.

For example:

<?php
$array = [ [1, 2], [3, 4],];

foreach ($array as list($a, $b)) {
    // $a contains the first element of the nested array,
    // and $b contains the second element.
    echo "A: $a; B: $b\n";
}
?>

output:

A: 1; B: 2
A: 3; B: 4

We can provide fewer elements in the list()  than there are in the nested array, in which case the leftover array values will be ignored:

<?php
$array = [
    [1, 2],
    [3, 4],
];

foreach ($array as list($a)) {
    // Note that there is no $b here.
    echo "$a\n";
}
?>

The above example will output:

1
3

A notice will be generated if there aren't enough array elements to fill the list():

================================================================

PHP Break and Continue

PHP Break

It was used to "jump out" of a switch statement.

The break 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 continuing 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:-

<?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;

   }

}


example: 

<?php

for ($i = 1; $i < 5; $i++) {

    for ($j = 1; $j <= $i; $j++) {

        echo " * ";

    }

    echo '<br />';

}

?>

Output:-

*
* *
* * *
* * * *


Example:- 

<?php

for ($i = 1; $i < 5; $i++) {

    for ($j = $i; $j < 5; $j++) {

       echo " * ";

   }

    echo '<br />';

}

?>

Output: -

* * * * 
* * * 
* * 


Example:-

<?php

for ($i = 1; $i < 5; $i++) {

    for ($j = $i; $j <= 5; $j++) {

        echo "&nbsp;"; // it will print blank space

    }

    for ($j = 1; $j <= $i; $j++) {

       echo " * ";

    }

    echo '<br />';

}

?>

Output

       * 
     * * 
    * * * 
   * * * * 



NESTED WHILE LOOP IN PHP :

  • While loops execute the statement repeatedly, till 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 statement, execution will not stop until the end of the iteration. 
  • Sometimes, if the while expression evaluates to FALSE from the very beginning, the statement won’t even be run once.


Syntax :


while(condition)
{
    while(condition)
     {
        statement(s);
        increment/decrements;
     }
    statement(s);
    increment/decrements;
}

Example:


<?php
int $i = 1 , $j = 1;
while( $i < 3 )
{
    while( $j < 3 )
    {
        echo ‘i am programmer  ‘;
        $j++;
    }
    echo ‘<br />’;
    $i++;
}
?>

Output:
i am programmer i am programmer
i am programmer i am programmer

===============================================================

NESTED DO WHILE LOOP 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 whereas it may not necessarily run with a regular while loop.

Syntax:


do
{
   statement(s);
   increment/decrements;
   do
   {
      statement(s);
      increment/decrements;
   }while( condition );
}while( condition );

Example:


<?php
int $i=1 , $j=2;
do
{
   do
   {
      echo ‘i am programmer  ‘;
      $j++;
   }while( $j < 3 )
   echo ‘<br />’;
   $i++;
}while( $i < 3 )
?>

Output:
i am programmer i am programmer
i am programmer i am programmer

====================================================================

NESTED FOR LOOP IN PHP :

Syntax:


for ( initialization; condition; increment/decrements )
{
   for ( initialization; condition; increment/decrements )
   {
      statement(s);
   }
   statement(s);
}

Example:


<?php
int $i , $j;
for( $i=1; $i<3; $i++ )
{
   for( $j=1; $j<3; $j++)
   {
      echo ‘i am programmer  ‘;
   }
   echo ‘<br />’;
}
?>

Output:
i am programmer i am programmer
i am programmer i am programmer




NESTED FOREACH LOOP IN PHP :

Syntax:


foreach(array as value)
{
   foreach(array as value)
   {
      Statement;
   }
   Statement;
}

Example:


<?php
$color= array( “Red”, “Green”, “Yellow”, );
$fruit = array( “Banana”, “Apple”, “Plum”, );
foreach ($color as $c)
{
   foreach ($fruit as $f)
   {
      echo “this is A $c $f .<br/>\n”;
   }
}
?>

Output:
this is A Red Banana.
this is A Red Apple.
this is A Red Plum.
this is A Green Banana.
this is A Green Apple.
this is A Green Plum.
this is A Yellow Banana.
this is A Yellow Apple.
this is A Yellow Plum.

===============================================

NESTED LOOPS EXAMPLE


Example

<?php

$n=5;

for($i=1; $i<=$n; $i++)

{

for($j=1; $j<=$i; $j++) 

{ echo $i ; 

echo “<br>"; 

}

?>

Output

1

22

333

4444

55555


Example

<?php

$n=1;

$row=5;

for($i=1; $i<=$row; $i++)

{

for($j=1; $j<=$i; ++$j)

{

echo " ";

echo $n;

echo" " ;

++$n;

}

 echo “<br>";

}

?>

Output

 1 

 2  3 

 4  5  6 

 7  8  9  10 

 11  12  13  14  15 


Example

<?php

$n=1;

$row=5;

for($i=1; $i<=$row; $i++)

{

for($j=5; $j>=$i; $j--)

{

echo " ";

echo $j;

echo" " ;

}

echo “<br>";

}

?>

Output

 5  4  3  2  1 

 5  4  3  2 

 5  4  3 

 5  4 

 5 


Post a Comment

0 Comments