Skip to main content

Create Arrays in PHP

You make an array in PHP by calling the array() function and listing the items inside it.

Example

Build $cars by calling array():

Prompt
Write a PHP script that creates an array with "Volvo", "BMW", and "Toyota" using the array() function.
Output: PHP script

Short Syntax

Tip: Square brackets [] do the same job with less typing:

Example

The same kind of array, this time written with []:

Prompt
Write a PHP script that creates an array with "Volvo", "BMW", and "Toyota" using the short bracket [] syntax.
Output: PHP script

Multiple Lines

PHP does not care about line breaks here, so you are free to spread an array over several lines, which often makes it easier to read:

Example

Prompt
Write a PHP script that creates an array with "Volvo", "BMW", and "Toyota" using the bracket [] syntax with each item on a separate line.
Output: PHP script

Trailing Comma

You may leave a comma after the final item, and PHP will accept it:

Example

Prompt
Write a PHP script that creates an array with "Volvo", "BMW", and "Toyota" using the bracket [] syntax with a trailing comma after the last item.
Output: PHP script

Array Keys

If you don't give an indexed array any keys, PHP assigns them for you: 0 for the first item, then one higher for each item after it. Spelling those keys out yourself produces exactly the same array as the earlier examples:

Example

Prompt
Write a PHP script that creates an indexed array with "Volvo", "BMW", and "Toyota" using explicit numeric keys 0, 1, and 2 with the bracket [] syntax.
Output: PHP script

Example

Written this way, it is clear that the two kinds of array share one form. The only difference is that an associative array has names where an indexed array has numbers:

Prompt
Write a PHP script that creates an associative array with keys "brand", "model", and "year" mapped to "Ford", "Mustang", and 1964 using the bracket [] syntax.
Output: PHP script

Declare Empty Array

An array doesn't have to be filled right away. Start with an empty one and put items in later:

Example

Prompt
Write a PHP script that declares an empty array and then adds "Volvo", "BMW", and "Toyota" to it using index numbers 0, 1, and 2.
Output: PHP script

Example

Associative arrays allow this as well: create the empty array first, then assign each key in turn:

Prompt
Write a PHP script that declares an empty array and then adds items with keys "brand", "model", and "year" set to "Ford", "Mustang", and 1964.
Output: PHP script

Mixing Array Keys

A single array can use numeric keys and named keys at the same time:

Example

Prompt
Write a PHP script that declares an empty array and adds items using both numeric indexes (0 and 1) and a named key ("fruit").
Output: PHP script