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 Build a Basic PHP Website (2018) Listing and Sorting Inventory Items Array Keys

Lars Segelke
Lars Segelke
3,049 Points

Why is the $isbn=key($books); into the foreach-loop wrong?

.

1 Answer

Erik McClintock
Erik McClintock
45,783 Points

Lars,

The syntax for writing this type of foreach loop in PHP is as follows:

foreach( $array as $key => $value ) {
    // code here
}

In this case, the challenge instructs us to call the "$key" variable "$isbn", since the keys of our $books array are the ISBN of the books. The "$value" variable is meant to be called "$book", because, well, the value of each item in our array is the title of that particular book! So, in the end, we wind up with:

foreach( $books as $isbn => $book ) {
    // code here
}

We target our array ($books), and say that we want each element to give us the $key (as a temporary variable named "$isbn") and the $value (as a temporary variable named "$book") for itself so that we can echo them out to the screen.

Hopefully this helps to clarify! As with a lot of errors that you'll come across, this one can be boiled down to syntax. Make sure you understand how to write the foreach loop as defined in the language, and then next make sure you're naming things as instructed in the challenge, and you should be on your way!

Erik