PHP : foreach Loop

In PHP, the foreach loop is used to iterate over arrays and objects. It provides an easy and convenient way to loop through each element in an array or each property in an object. Here's the basic syntax:


foreach ($array as $value) {
    // code to be executed for each iteration
}
 

In this syntax:

  • $array is the array you want to iterate over.
  • $value is a variable that will hold the value of the current element in each iteration.

Here's an example of using foreach with an array:


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

foreach ($colors as $color) {
    echo "$color <br>";
}

 

This will output:


red
green
blue

 

You can also use foreach with associative arrays to iterate over key-value pairs:


$ages = array("Peter" => 32, "John" => 28, "Doe" => 45);

foreach ($ages as $name => $age) {
    echo "$name is $age years old <br>";
}

 

This will output:


Peter is 32 years old
John is 28 years old
Doe is 45 years old

 

You can also use foreach with objects:


class Person {
    public $name;
    public $age;

    function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }
}

$person1 = new Person("Alice", 30);
$person2 = new Person("Bob", 35);
$person3 = new Person("Charlie", 40);

$people = array($person1, $person2, $person3);

foreach ($people as $person) {
    echo $person->name . " is " . $person->age . " years old <br>";
}

 

This will output:


Alice is 30 years old
Bob is 35 years old
Charlie is 40 years old

Remember, foreach iterates over each element in the array or each property in the object, executing the specified code block for each iteration.