foreach
The foreach loop in PHP allows you to iterate over the elements of an array and execute a block of code for each element.
Here is the general syntax for a foreach loop in PHP:
foreach ($array as $value) {
code to be executed;
}
You can also specify the key of each element in the array by using the following syntax:
foreach ($array as $key => $value) {
code to be executed;
}
Here is an example of a foreach loop that iterates over an array of numbers and prints each element:
$numbers = array(1, 2, 3, 4, 5);
foreach ($numbers as $number) {
echo "$number ";
}
In this example, the foreach loop will iterate over the elements of the $numbers array, assigning each element to the $number variable in turn and executing the code inside the loop. The code inside the loop will print the value of $number on each iteration.
Here is an example of a foreach loop that iterates over an associative array and prints each key and value:
$students = array(
"student1" => "John",
"student2" => "Jane",
"student3" => "Bob"
);
foreach ($students as $student_id => $name) {
echo "Student ID: $student_id, Name: $name <br>";
}
In this example, the foreach loop will iterate over the elements of the $students array, assigning the key of each element to the $student_id variable and the value of each element to the $name variable, and executing the code inside the loop. The code inside the loop will print the value of $student_id and $name on each iteration.