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 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,526 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.