Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

modify the code inside the foreach loop to display the $isbn in parentheses. After the title, add a space, an opening parenthesis, the ISBN, and a closing parenthesis.

I'm having trouble with this code challenge. I can't figure out how to get the ISBN number. I'm having a bit difficulty understadning the array key. Can someone help? thank you [code] <?php

$books["978-0743261690"] = "Gilgamesh"; $books["978-0060931957"] = "The Odyssey"; $books["978-0192840509"] = "Aesop's Fables"; $books["978-0520227040"] = "Mahabharta"; $books["978-0393320978"] = "Beowulf";

?><html> <head> <title>Five Great Books</title> </head> <body> <h1>Five Great Books</h1> <ul> <?php foreach($books as $isbn => $book) { ?> <li><?php echo $book . " " $book["isbn"]; ?></li> <?php } ?> </ul> </body> </html>

3 Answers

The $isbn is a key and $book is a value.

When working with an array, you have a name for the array, in this case, $books and then in the database, you have each "item" that's stored within the array.

Now, you need to have a "locator" for each corresponding bit of data. This is the "key". So, when you want the values of the array, you just go:

foreach($books as $value)

PHP knows that when you're using foreach, you're saying look in this array ($books) and each time you come across a "location" (the key), get me the bit of data that is there, the value.

However, when we want the key as well, because usually the key is just 0,1,2,3,4 etc....very boring...we need to tell PHP that we'd like the "location" (key) for each value.

So, what do we need to ask PHP to do when we want the keys of the values, because we've given them interesting names?

We tell PHP this: look in the $books array, and for each value that you find, please can I have the key for the value as well.

Looks something like this:

foreach($array as $key => $value)

Hope that helps!

Because $book is the value that's stored in the key of $isbn. $book['isbn'] doesn't exist but you could do something with $isbn['title'] or something similar.

Hi there, thanks a lot. This really helped!

I was able to play around until I got it to work with. <?php echo $book; ?> <?php echo $isbn; ?>

I'm not completely sure why it's just $isbn and not $book["isbn"]

thanks for helping!