Using PHP For Loop and Switch Conditional Statement

This is just a revision of using PHP for loop and switch conditional case statement after somebody ask me a very simple question of how to use them together today.

The following PHP codes are a very typical example of using for loop and switch conditional case statement together. I think you should use them this way for many many times. Let’s just get a quick and brief revision.

 <?php

$var4 = "Alex";
$var5 = "Kathy";

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

    switch ($i){
        case 4:
            echo "This is: " . $i;
            .......................
            ... more codes here ...
            .......................
            break;
        case 5:
            echo "This is: " . $i;
            ........................
            ... more codes here ...
            ........................
            break;        
    } // end switch statement

    echo "<br>";
    echo "The person is: " . ${"var".$i};
    echo "<br>";
} // end for loop

?>

This is very clear that the PHP for loop will run two times, and different codes will be executed depend on the value of i with the using of switch conditional statement.

The output of the above codes are:

This is: 4
The person is: Alex
This is: 5
The person is: Kathy

Please note how we can get the value of a variable as below:

${"var".$i};

 

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>