Example of foreach loop in php



<html>
    <head>
        <title>Loops: foreach</title>
    </head>
    <body>
   
    <?php
        $ages = array(43, 83, 125, 126, 223, 242);
    ?>

    <?php
        // using each value
        foreach($ages as $age) {
            echo $age . ", ";
        }
    ?>
    <br />
    <?php
        // using each key => value pair
        foreach($ages as $position => $age) {
            echo $position . ": " . $age . "<br />";
        }
    ?>
    <br />
    <?php
             $prices = array("Brand New Computer"=>2000,
        "1 month in "=>25,
        "Learning PHP" => "priceless");
        foreach($prices as $key => $value) {
            if (is_int($value)) {
                echo $key . ": $" . $value . "<br />";
            } else {
                echo $key . ": " . $value . "<br />";
            }
        }
    ?>


    </body>
</html>

0 comments:

Post a Comment

Subscribe to RSS Feed Follow me on Twitter!