Jump to content
Larry Ullman's Book Forums

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 post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...