kravmaguy Posted September 18, 2018 Share Posted September 18, 2018 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>'; ?> Link to comment Share on other sites More sharing options...
Larry Posted September 27, 2018 Share Posted September 27, 2018 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. Link to comment Share on other sites More sharing options...
Recommended Posts