PHP “foreach” loop is designed to iterate over each element within an array. It starts with the keyword “foreach” which is encapsulated by parentheses and a pair of curly braces.

Inside the parentheses, you declare the array you wish to traverse and assign a temporary variable to store the value of each array element during the iteration process.

Here is a quick example.

$colors = array("red", "green", "blue");

foreach ($colors as $color) {
    echo $color;
}

Alternatively, to access both the key and the value:

foreach( $array_table as $value => $key ) {
 // statements 
}

Additionally, there is another structure for the PHP “foreach” loop, like the one below.

foreach( $array_table as $value ) {
 // statements 
}

In the next part, I’ll show you how it works with some examples. Let’s dive in.

How does it work?

In the below figure, you will understand how it works.

PHP Foreach Loop

The PHP foreach loop works by iterating over each element in an array and executing a block of code for each iteration. It accomplishes this by using a set of predefined syntax rules that define how the loop should behave.

The foreach loop executes by taking the array to iterate over and assigning the value of the first element to a new variable. You define this variable in the loop declaration to hold the value of each element in the array as the loop progresses.

Next, the code inside the loop’s curly braces is executed, which can be any valid PHP code. This code typically performs some operation on the current element of the array, such as printing its value to the screen or manipulating it in some way.

Once the code inside the curly braces executes, the loop proceeds to the next element in the array and assigns the variable to that element’s value. It repeats this process for every element in the array until there are no more elements to iterate over.

One important thing to note is that the variable defined in the loop declaration is a new variable that is created each time the loop runs. It is not a reference to the original array, so any changes made to the variable within the loop will not affect the original array.

Anyway, in the next section, I will focus on how to write embedded “foreach” with HTML markups.

Embedded PHP Foreach with HTML or JavaScript

The embedded foreach can work with HTML page in separate areas:

<?php 
  $tuts = array( "PHP", "HTML", "JavaScript" );
  foreach( $tuts as $tutorial ):
?>
<h1>CodedTag.com <?= $tutorial; ?> Tutorial</h1>
<?php endforeach; ?>

This code will print all tutorial names inside the array using the HTML heading tag with a repeated loop.

Using PHP Foreach by Reference

To use the PHP foreach by reference you have to use the & (and) operator in the extracted item. For example.

<?php
   $arr = array("item 1", "item 2");
   foreach( $arr as &$value ){
     echo $value;
   }
?>

You can also use the array directly in the foreach loop.

<?php
   foreach( $arr as &$value ){
     echo $value;
   }
?>

Foreach with Associative Array

To facilitate easy retrieval, associative arrays use names or numbers as index fields. During iteration with a foreach loop, you can extract keys and values separately. Take the following example into consideration.

<?php
   
   $assoc_array = array(  
      "name" => "Ahmed", 
      "age"  => 20,
      "job"  => "Web Developer"
   );
   
   foreach( $assoc_array as $key => $value ){
      echo $key . " : " . $value;
      echo "\n";
   }

?>

I separated the keys and values in this instance, resulting in the following output.

name : Ahmed
age : 20
job : Web Developer

During the foreach loop, each item can be accessed and the corresponding $key and $value of the array can also be accessed.

No Curly Braces with PHP Foreach

It is possible to use the PHP foreach loop without curly braces, resulting in the loop only executing the first statement and disregarding any subsequent lines.

The following example will solely display the names contained in the array based on the first statement. The second statement will be disregarded by the foreach loop.

<?php
  
  $array = array( "Ahmed", "Samy", "Montasser", "Michael" );
  foreach( $array as $arr )
    echo $arr; // execute this line only as in the loop
    echo "This line will not be executed."; // ignore this line

?>

Wrapping Up

Throughout this article, you have gained an understanding of how to utilize the PHP foreach loop, with various examples provided including associative array with foreach, one line statement, and indexed array with foreach.