How to use foreach to loop through a two-dimensional array in PHP?
In PHP, you can use a foreach loop to iterate through a two-dimensional array. Below is an example code:
$students = array(
array("name" => "Alice", "age" => 20),
array("name" => "Bob", "age" => 21),
array("name" => "Charlie", "age" => 22)
);
foreach ($students as $student) {
foreach ($student as $key => $value) {
echo $key . ": " . $value . "<br>";
}
echo "<br>";
}
Output/result:
name: Alice
age: 20
name: Bob
age: 21
name: Charlie
age: 22
In the example above, $students is a two-dimensional array containing information for three students. The outer foreach loop iterates through each student, while the inner foreach loop iterates through the specific information (key-value pairs) for each student. By using $student as the loop variable, you can access the information for each student sequentially.