This question already has answers here:
Answer
Solution:
Read foreach manual
There are two syntaxes for foreach
foreach (iterable_expression as $value)
statement
foreach (iterable_expression as $key => $value)
statement
From php.net,
The first form traverses the iterable given by iterable_expression. On each iteration, the value of the current element is assigned to $value.
The second form will additionally assign the current element's key to the $key variable on each iteration.
I would rewrite your code like this
printEach($movies);
function printEach($array) {
echo "<br><br>";
foreach ($array as $key => $value) {
echo $key;
if (is_array($value)) {
printEach($value); // Recursive
} else {
echo " - ".$value."<br><br>";
}
}
}
Answer
Solution:
You can use the key syntax in the for each loop
foreach ($movies as $genreName => $genres) {
echo "$genreName <br>";
while (list ($index, $array) = each ($genres)) {
echo "Movie number: $index <br>";
while (list ($k, $v) = each ($array)) {
echo "$k - $v <br>";
}
echo "<br>";
}
echo "<br>";
}
Source