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 Simple PHP Application Listing Inventory Items Creating the Products Array

key and the order of "foreach" loop

Not sure if key has anything to do with the order that foreach progress... But if I wrote something like this: $products = array(); $products[4] = "Logo Shirt, Red"; $products[3] = "Mike the Frog Shirt, Black"; $products[2] = "Mike the Frog Shirt, Blue"; $products[1] = "Logo Shirt, Green";

Turns out "Logo Shirt, Red" still gets displayed first. But based on what I learnt from other language, "Logo Shirt, Green" should come first...

Kinda confusing here....

1 Answer

Hugo Paz
Hugo Paz
15,622 Points

HI Yaxin,

You are passing a key to the value in the array. This key is independent of the inner pointer php uses to tell in which position an element is in the array.

If you do a var_dump() of that array you get this:

array(4) { [4]=> string(15) "Logo Shirt, Red" [3]=> string(26) "Mike the Frog Shirt, Black" [2]=> string(25) "Mike the Frog Shirt, Blue" [1]=> string(17) "Logo Shirt, Green" }

You can see the key (between the square brackets) with the corresponding value.