Looping Constructs

While Loop

<?php
    $i = 0;
    while($i++ < 10) {
        echo $i . " ";
    }

// or 


 $i = 0;
    while($i < 10) {
        echo $i . " ";

        $i++; // In last chapter we saw it is increment operator
    }


?>

Output

1 2 3 4 5 6 7 8 9 10

Do while

<?php

    $i = 0;
    do {
        echo $i . " ";
    } while($i++ < 10);

?>

Output

0 1 2 3 4 5 6 7 8 9 10

Can you spot the difference between "do while" and "while". Try this out as Homework.

For Loop

<?php

    for($i=0; $i<10; $i++) {
        echo $i . " ";
    }

?>

Output

0 1 2 3 4 5 6 7 8 9 10

Break/Continue

<?php
    for($i=0; $i<10; $i++) {

        if($i==5) { continue; }

        if($i==8) { break; }

        echo $i . " ";
    }
?>

Output

0 1 2 3 4 6 7

break exits the loop and continue skips the loop without ending or breaking it.

Note that break and continue can take a level argument that tells them how many levels to break or continue out of.

Nested Loops

<?php

    $done = false;

    while(!$done) {

        for($i=0; $i<10; $i++) {

            if($i==8) { break 2; }

            echo $i . " ";

        }

    }

?>

Here break is given argument 2, that means exit from 2 level down, that is, first "for" and second "while" loop.

What will happen, if break is given no argument like break 2; ? Well, it will be infinite loop, that means, this loop will never ever end and will keep on running until it is forcefully stopped or otherwise.

Current Output

0 1 2 3 4 5 6 7

 Foreach Loop

<?php

    $arrayValue = array (1,2,3,4,5,56,67);


    foreach($arrayValue as $value) {
        echo $value.' ';
    }

// Or , each array has unique key, if not specified it starts from 0 index .

    foreach($arrayValue as $key => $value ) {

        echo "Key or \$arrayValue position {$key} has {$value} Value";

    }

?>

Array value can be easily printed out using  foreach loop . In Second foreach loop, you can see , I am using \$arrayValue , this is done in-order to escape parsing or variable, as you can see, The whole string is enquoted in double quotes, that means, any variable passed inside it will be parsed and value of variable will be shown, but i don't want to print value of $arrayValue  as it is an array and we will get value as "Array" , plus, i wanted to show variable name in output, so i escaped $ with "\".

 

 


Loading ...

Related Results :

  1. For & While Loops
  2. Looping Constructs
  3. Loop Constructs & Control
  4. While Loop
  5. Do While loop
  6. For Loops in Java
  7. Python Loop
Note :
  • Related Posts are generally User Blog posts.
  • or Other tutorials from other networks of w3clan.com.
  • Any registered user can create related posts based on search term tags.

About the Author