Indexed Arrays
7 min · PHP
PHP arrays hold many values in order — indexed from zero.
Enemy 1 of 5
What an array is for
So far every variable you've made has held exactly one value. An array changes that: it's a single variable that holds an ordered collection of values, so instead of juggling $fruit1, $fruit2, $fruit3 you can keep them together as one $fruits array.
You can build one with the array("a", "b") function-style syntax, or the shorter, more modern ["a", "b"] bracket syntax — they're completely equivalent, and the bracket form is what you'll see in almost all PHP code written in the last decade.
Each value in the array gets an automatic numeric position called an index, and — this catches almost everyone the first time — PHP counts indexes starting at 0, not 1. So in ["apple", "banana", "cherry"], "apple" is at index 0, "banana" is at index 1, and "cherry" is at index 2. You read a value back out with square brackets after the variable name, like $fruits[0].
Loading editor...