Google News
logo
PHP Program to foreach loop
The `foreach` loop is a type of loop statement in PHP that allows you to iterate over the elements of an array or an object.

The basic syntax of a `foreach` loop in PHP is as follows:
foreach ($array as $value) {
    // code to execute for each element in the array
}​
In this syntax, `$array` is the array that you want to iterate over, and `$value` is a variable that will be assigned the value of each element in the array as you loop through it.

For each iteration of the loop, the code inside the loop is executed, with `$value` representing the current element of the array.

Here's an example of a PHP program that uses a `foreach` loop to iterate over an array of names and print each name :
Program :
<?php
    // This is a PHP program that uses a foreach loop to print an array of names
    
    $names = array("Alice", "Bob", "Charlie", "Dave");
    
    foreach ($names as $name) {
        echo $name . " ";
    }
?>
Output :
Alice Bob Charlie Dave
In this code, the array `$names` contains four elements, each representing a name. The `foreach` loop iterates over the array, with `$name` representing the current element.

The code inside the loop simply prints `$name`, followed by a space.

After each iteration of the loop, `$name` is assigned the value of the next element in the array, until all elements in the array have been processed.

This demonstrates how `foreach` loops can be used to iterate over the elements of an array or an object, and perform a specific action for each element.