start learning
Image 1

PHP Foreach loop

A PHP Foreach loop is used exclusively for iterating over arrays and other iterable objects. It simplifies the process of iterating through each element of an array or collection without the need for an explicit index.


Basic Syntax of Foreach Loop

The basic syntax of "Foreach" Loop in PHP is as follows:


foreach ($array as $value) {
    // Code to be executed for each element in $array
}
 

Iterating Over an Indexed Array


$colors = array("Red", "Green", "Blue");

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


Iterating Over an Associative Array (Key-Value Pair)


$person = array("Name" => "John", "Age" => 30, "Location" => "New York");

foreach ($person as $key => $value) {
    echo "$key: $value\n";
}
 


Iterating Over a Multidimensional Array


$students = array(
    array("Name" => "Alice", "Grade" => "A"),
    array("Name" => "Bob", "Grade" => "B"),
    array("Name" => "Charlie", "Grade" => "C")
);

foreach ($students as $student) {
    echo $student["Name"] . " got a " . $student["Grade"] . " grade.\n";
}


These examples illustrate how PHP foreach loops simplify the process of iterating through arrays and associative arrays, making it easier to work with data structures in your PHP code.