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.
PHP Foreach loop
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 . " ";
}
- In this example, we have an indexed array called $colors with three elements.
- The foreach loop is used to iterate over each element in the array.
- In each iteration, the current element's value is assigned to the variable $color.
- The loop then executes the code block inside, which echoes the value of $color followed by a space.
- The loop iterates through all elements in the array, printing "Red Green Blue ".
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";
}
- Here, we have an associative array called $person with key-value pairs representing personal information.
- The foreach loop iterates over each element in the array.
- In each iteration, the current key is assigned to the variable $key, and the current value is assigned to the variable $value.
- The loop executes the code block inside, which displays the key and its corresponding value.
- The loop iterates through all key-value pairs, producing output like:
Name: John
Age: 30
Location: New York
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";
}
- In this example, we have a multidimensional array called $students, where each element is an associative array representing a student's name and grade.
- The foreach loop iterates over each element (student) in the outer array.
- In each iteration, the current student (an associative array) is assigned to the variable $student.
- The code block inside the loop uses $student to access the "Name" and "Grade" keys and displays the student's name and grade.
- The loop iterates through all students, providing output like:
Alice got a A grade.
Bob got a B grade.
Charlie got a C grade.
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.
×