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 Adding Elements and Specifying a Key

Are array elements displayed in sequence numerically?

I am wondering why Clean Code isn't displayed 2nd on the list when we echo to the screen? Since we are declaring our own indexes, and clean code is the 2nd lowest, shouldn't it display second on the screen?

1 Answer

andren
andren
28,558 Points

Here is a quote from the PHP Language Specification:

An array is represented as an ordered map in which each entry is a key/value pair that represents an element. An element key can be an expression of type int or string. Duplicate keys are not permitted. The order of the elements in the map is the order in which the elements were inserted into the array.

The last sentence is the key part. Arrays are ordered by the order that elements where inserted into it. The keys are just treated as labels, regardless of whether those labels are numbers or strings.

It's important to note though that there are a bunch of built-in functions for sorting arrays, which you can find on the official Sorting Arrays documentation page.