How to use the for-each loop with simple values In PHP

We can use the foreach loop to access and use the elements in an array of simple values, such as strings or numbers.

Example 1: In this example we iterates over the $names array with foreach, printing each name followed by a line break (<br>), resulting in a list of names displayed on separate lines.

PHP
<?php
    $names = array("Ramesh", "Suresh", "Ram", "Shyam");
    foreach ($names as $value) {
    echo "$value <br>";
    }
?>

Output:

Ramesh
Suresh
Ram
Shyam

In the above example, each element of the array names is iterated over and is assigned to the variable value.

Example 2: In this example we iterates over the $marks array using foreach, printing each mark followed by a line break (<br>), resulting in each mark displayed on a new line.

PHP
<?php
    $marks = array(45, 78, 93, 69);
    foreach ($marks as $value) {
      echo "$value <br>";
    }
?>

Output:

45
78
93
69

How to check foreach Loop Key Value in PHP ?

In PHP, the foreach loop can be used to loop over an array of elements. It can be used in many ways such as

Table of Content

  • Using the for-each loop with simple values
  • Using the foreach loop with Key-Value pairs
  • Using array_keys Function to Access Keys and Values

Similar Reads

Using the for-each loop with simple values

We can use the foreach loop to access and use the elements in an array of simple values, such as strings or numbers....

Using the foreach loop with Key-Value pairs

We will use the same foreach loop to iterate over an array of key-value pairs....

Using array_keys Function to Access Keys and Values

In this new approach, we will use the array_keys function to access the keys directly and then use those keys to access the corresponding values....

Contact Us