Skip to main content

PHP Indexed Arrays

Every item in an indexed array is identified by a number, its index.

Counting starts at 0: the first item is at index 0, the next at index 1, and the numbers keep going up from there.

Example

Build an indexed array and print its contents with var_dump():

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

Access Array Item

Use the index number inside brackets to read one particular item.

Example

Print the item at index 0, the first car:

Prompt
Write a PHP script that creates an indexed array with "Volvo", "BMW", and "Toyota", then prints the first item using its index number.
Output: PHP script

Change Value of Array Item

To give an item a new value, assign to its index number:

Example

Replace the second item, at index 1:

Prompt
Write a PHP script that creates an indexed array with "Volvo", "BMW", and "Toyota", changes the second item to "Ford", then displays the array with var_dump().
Output: PHP script

Loop Through an Indexed Array

A foreach loop goes through the array one item at a time, which makes it easy to print everything:

All the array functions are described in our PHP Array Reference.

Example

Print each car on its own line:

Prompt
Write a PHP script that creates an indexed array with "Volvo", "BMW", and "Toyota", then uses a foreach loop to print each item followed by an HTML line break.
Output: PHP script