Indexed Arrays
Indexed Arrays: Numbers as Keys
Indexed arrays are the simplest type of array in PHP. Each item gets a number (called an index) that identifies its position. By default, PHP starts counting at 0, so the first item is $array[0], the second is $array[1], and so on.
Accessing and Changing Values
You access items by their index number in square brackets: $cars[0] gives you the first car. You can change values the same way: $cars[1] = "Ford" replaces the second item. It's straightforward and direct.
Looping Through Indexed Arrays
The foreach loop is your best friend here. It automatically goes through each item in order without you needing to track index numbers manually. This is cleaner and less error-prone than using a for loop with counters.
How Index Numbers Work
PHP automatically assigns index numbers starting from 0, but you can also assign them manually. If you create an array like $cars[5] = "Volvo" and $cars[14] = "Toyota", PHP doesn't fill in the gaps — those index positions simply don't exist.
When you add new items using array_push(), PHP looks at the highest existing index number and adds one. So if your highest index is 14, the new item becomes index 15, even if you have gaps in your numbering.
Indexed arrays are perfect for lists where order matters but the items don't need descriptive labels. WordPress uses them for things like lists of post IDs, arrays of taxonomy terms, and menu item orders. You'll see them constantly in query results and API responses.