Foreach loop in PHP

PHP foreach Loop
  • The foreach loop is used through a block of code for each element in an array.
  • The foreach loop works only on arrays, and is used to loop through each value pair in an array.
  • Syntax
  • foreach (array as value) {
    code to be executed;
    }

    <!DOCTYPE html>
    <html>
    <body>
    <?php
    $bike = array("BMW", "Yamaha", "suzuki");
    foreach ($bike as $value) {
    echo "$value </br>";
    }
    ?>
    </body>
    </html>
    
  • example
  • <!DOCTYPE html>
    <html>
    <body>
    <?php
    $bike_price = array("BMW S 1000 RR"=>"Rs. 18.50 lakh", "BMW F 900 R	"=>"Rs. 9.90 lakh", "BMW R 1250 RT	"=>"Rs. 22.50 lakh");
    foreach($bike_price as $x => $value) {
    echo "$x = $value </br>";
    }
    ?>
    </body>
    </html>
    


  • example
  • <!DOCTYPE html>
    <html>
    <body>
    <?php
    $price = array( 104, 205, 300, 450, 570);
    foreach( $price as $val ) {
    echo "Price is $val </br>";
    }
    ?>
    </body>
    </html>
    
Related Posts :