Foreach Loop [#27] Code Dynamic Websites with PHP

Lecture 27: Foreach Loop

The Foreach Loop! This loop is a very popular loop, and is used extensively in database-driven websites. The purpose of a Foreach Loop is to “loop through each key/value pair in an array” (w3schools).

The syntax looks like so:

foreach ($array as $value) {

// execute code


Basically, here’s what happens during each loop iteration:

Assign value of current array element to $value
$value is echoed on the screen
The array pointer then moves to the next element within the array
Repeat from beginning until final array element
Let’s use a real-world example of how to use a Foreach Loop:

// We need to create an array

// Let’s resurrect our array of moustaches

$moustaches = array(“Handlebar”, “Salvador Dali”, “Fu Manchu”);

// Loop through the $moustaches array

foreach ($moustaches as $moustache) {

// Output each individual value

echo “I love the $moustache. “;


If coded correctly, this should echo the three moustaches in the array on your screen.



Xem thêm bài viết khác:

4 thoughts on “Foreach Loop [#27] Code Dynamic Websites with PHP”

  1. how to put this thing in the function and the starting of every element put echo i am facing some huge difficulties,please help me out

    <div class="col-lg-4 feature">
    <div class="panel">
    <div class="panel-heading">
    <h3 class="panel-title">
    <a href="shirt.php?id=<?php echo $product_id; ?>" class="btn btn-lg btn-info btn-block">
    <span class="glyphicon glyphicon-th-large"></span> View Details
    <a href="shirt.php?id=<?php echo $product_id; ?>"><img src="<?php echo $product["img-sm"]; ?>" alt="<?php echo $product["name"]; ?>" ></a>
    <div class="label label-info price"><span class="glyphicon glyphicon-tag"></span> <sup>$</sup><?php echo $product["price"]?></div>


Leave a Comment