All lessons

Indexed Arrays

7 min · PHP

PHP arrays hold many values in order, indexed from zero.

PHP · Indexed Arrays0/5 cleared

Enemy 1 of 5

What an array is for

This makes an array holding three fruits and prints the first one. Indexes start at 0, so $fruits[0] is apple. Press Run to see it.

Why this works

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].

You
Kernel Hellhound
Loading editor…
Sign up to fightThis one runs on our servers, so it needs a free account.