Jump to content
Larry Ullman's Book Forums
Sign in to follow this  
kravmaguy

help with page 177

Recommended Posts

I put in this code at the end of the exercise to try to help me understand it better, 

1. when I print $books it gives me the entire array this i expected

2. print_r($book); only gives me the Last book? 

3. print_r($chapter); prints all the books?

4. print_r($key); prints only the last key in the $chapters array which is really a book? 

5. print_r($value); prints only the last value in the $chapters array which is value of the last $key

I am hoping someone can explain this to me and why it does this. 


foreach ($books as $book => $chapter) {
	print "<p>$book";
		foreach ($chapter as $key => 
		$value){
		print "</br>chapter $key is $value";
		}
	print "</p>";

}

echo '<pre>';
print_r($books);
echo  '</pre>';

echo '<pre>';
print_r($book);
echo  '</pre>';

echo '<pre>';
print_r($chapter);
echo  '</pre>';

echo '<pre>';
print_r($key);
echo  '</pre>';


echo '<pre>';
print_r($value);
echo  '</pre>';
?>

 

Share this post


Link to post
Share on other sites
On 9/18/2018 at 5:10 PM, kravmaguy said:

2. print_r($book); only gives me the Last book? 

Yep! After the loop, $book refers to the last item in the $books array.

On 9/18/2018 at 5:10 PM, kravmaguy said:

3. print_r($chapter); prints all the books?

That should not be the case! I wouldn't think it'd be the case, anyway. Just to be clear, you may want to add headings before doing each print_r() so it's absolutely clear what's going on. 

On 9/18/2018 at 5:10 PM, kravmaguy said:

4. print_r($key); prints only the last key in the $chapters array which is really a book? 

It should print the last key, yes, but that value should not be a book.

On 9/18/2018 at 5:10 PM, kravmaguy said:

5. print_r($value); prints only the last value in the $chapters array which is value of the last $key

Yes, that should be correct. 

Aside from a bit of confusion, in general, the last value assigned to a variable in the loop is still assigned to that variable after the loop, which is what you're seeing here.

 

Share this post


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.

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...
Sign in to follow this  

×
×
  • Create New...