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

General Discussion

Array Keys (Key in foreach loop)

Hey! I'm a total n00b at PHP, but the lessons are really helping me finally understand! I've gotten my head around everything so far, except one thing is puzzling me.

In these two coding instances-

foreach($products as $product_id => $product)

foreach($books as $isbn => $book)

How do $product_id and $isbn produce the same result (essentially)? At first, product_id made sense since $product is the name of the array and I thought maybe id was a php specific identifier, but then $isbn did the same thing so now I am confused as to how this works.

Please explain like I'm 5.

Thank you!

1 Answer

Hey Amanda,

So the standard way to write this is

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

This is for an array type that in some languages would be known as a hash or a hashmap.

$array = array( "book1" => "Great Gatsby", "book2" => "Farewell to Arms", );

So, when you are within the loop, the names of the $key and the $value are any variable names you want to use, for example.

foreach($array as $book=> $value){ print $book . " | ". $value; }

Will output:

book1|Great Gatsby book2|Farewell to Arms

Does that make any sense?