Jump to content
Larry Ullman's Book Forums

Nailing Down The Foreach Loop.


Recommended Posts

Greetings,

 

I think I understand the logic flow inherit in nested foreach loops. However, I'd like to be sure. I've annotated a nested foreach from this book with my understanding of its function commented in with the code. Insights would be appreciated.

 

foreach ( $books as $title => $chapters ) # Look at the first key/value pair in $books. Assign the key to $title and the value to $chapters (in this case, the value is another array). The $chapters variable holds the T2 array, and carries it down to the nested foreach loop.

{

print
"<p>
$title
";
# Print the key (in this case, a string).
foreach
(
$chapters
as
$number
=>
$chapter
)
# Look at the first key/value pair in the T2 array. Assign the key to $number and the value to $chapter. In this case the value is a string.
{
print
"<br />Chapter
$number
is
$chapter
";
# Print the key and the value (associative array, they are both strings).
}
# The nested foreach loop will auto-increment through each key/vaue pair in the T2 array before exiting. Once exited flow is handed back up to the T1 foreach loop.
print
'</p>';
} # Repeat this process for each key/value pair in the T1 array level via auto-increment.

unset($title, $chapters, $chapter, $number); # Clear all of the dummy variables used so they do not affect later constructs.

 

 

Thanks

Link to comment
Share on other sites

 Share

×
×
  • Create New...