Looping through Multi dimensional array in PHP
Here is a small chunk of code to understand the basic implementation of Looping through Multi dimensional array in PHP!
<!DOCTYPE html>
<html>
<head>
<title>Foreach loop through multidimensional array</title>
</head>
<body>
<?php
$employees = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2,3),
array("Land Rover",17,15)
);
$keys = array_keys($employees);
echo "Keys are ";
for($i = 0; $i < count($employees); $i++)
{
echo $keys[$i]. ",";
}
echo "<br>"."<br>";
echo "Number of subarrays: " .count($employees)."<br>";
for($i = 0; $i < count($employees); $i++)
{
echo "<br>";
echo "Values of subarray $keys[$i] " . "<br>";
foreach($employees[$keys[$i]] as $value) {
echo $value . "<br>";
}
echo "<br>";
}
?>
</body>
</html>
So there are 4 subarrays which means that there are 4 keys! In this scenareo the key value is already decided! We don't have to implicitly do that. Here "$employees[$keys[$i]] as $value" is making sure that the sub arrays are accessed one by one according to the count "i" . To make sure that whatever the number of values are in different arrays , they all must be printed , we need to use foreach loop which will iterate all the sub arrays according to their sizes.
Output :