Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,782 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