PUBLISHED ON: AUGUST 12, 2021
Foreach loop through multidimensional array in PHP
Answer: Using nested loop
A multi-dimensional array in PHP is an array consists of one or more arrays. We can access or retrieve the elements of a multi-dimensional array using the foreach loop along with the for loop.
Example: foreach loop through multi-dimensional array
In the given example, we have accessed the elements of the multi-dimensional array using for loop along with the foreach loop.
<!DOCTYPE html>
<html>
<head>
<title>Foreach loop through multidimensional array</title>
</head>
<body>
<?php
$employees = array (
array("Name" => "Harry", "Age" => 25, "Department" => "Management"),
array("Name" => "Jack", "Age" => 31, "Department" => "Developer"),
array("Name" => "Harry", "Age" => 35, "Department" => "Developer")
);
$keys = array_keys($employees);
for($i = 0; $i < count($employees); $i++) {
echo "<br>";
foreach($employees[$keys[$i]] as $key => $value) {
echo $value . "<br>";
}
echo "<br>";
}
?>
</body>
</html>
Output
We can also access the elements of the multi-dimensional array using the nested foreach loop. Here, we have used the nested foreach loop to iterate through every item in every array inside the array $employees and then print them using the echo.
Example: foreach loop through multi-dimensional array
In the given example, we have used the nested foreach loop to iterate through every element within the given multi-dimensional array.
<!DOCTYPE html>
<html>
<head>
<title>Foreach loop through multidimensional array</title>
</head>
<body>
<?php
$employees = array (
array("Name" => "Harry", "Age" => 25, "Department" => "Management"),
array("Name" => "Jack", "Age" => 31, "Department" => "Developer"),
array("Name" => "Harry", "Age" => 35, "Department" => "Developer")
);
foreach ( $employees as $employee ) {
foreach ( $employee as $key => $value ) {
echo "$value";
echo "<br>";
}
echo "<br>";
}
?>
</body>
</html>
Output
Conclusion
In this lesson, we have learned how to loop through multi-dimensional arrays in PHP. Here we have discussed two methods to access all the array elements of the multi-dimensional array. At first, we have accessed elements of the given array using the for loop along with the foreach loop. After that, we have used the nested foreach loop to access the elements of the given multi-dimensional array.