Skip to main content

PHP Access Array Items

How you read an item depends on the kind of array: an indexed array wants the item's index number, while an associative array wants its key name.

Example

Put the index number in square brackets to read that item:

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

Access Associative Array Item

Note: Counting starts at 0, so index 0 is the first item. That is why $cars[2] above gave the third car.

Associative arrays work the same way, except the key name goes between the brackets:

Example

Read the year item by naming its key:

Prompt
Write a PHP script that creates an associative array with keys "brand", "model", and "year" for a car, then prints the year value.
Output: PHP script

Double or Single Quotes

Key names in brackets may be written with either kind of quotes, double or single. Both lines below read the same item:

Example

Prompt
Write a PHP script that creates an associative array for a car and accesses the "model" key using both double and single quotes.
Output: PHP script

Execute a Function Item

Since an item can be any data type, it can be a function too.

Here the item holds the function's name. To call it, write the index number and then add parentheses ():

Example

Call the function stored at index 2:

Prompt
Write a PHP script that defines a function, stores its name as a string in an indexed array alongside other values, then calls that function using the array index followed by parentheses.
Output: PHP script

Example

With an associative array, the key name takes the place of the index:

Prompt
Write a PHP script that defines a function, stores its name as a string in an associative array, then calls that function using the key name followed by parentheses.
Output: PHP script

Loop Through an Associative Array

A foreach loop is the way to go through an associative array and print every value it holds:

Example

Print each key together with its value:

Prompt
Write a PHP script that creates an associative array for a car with brand, model, and year, then uses a foreach loop to print each key and value followed by an HTML line break.
Output: PHP script

Loop Through an Indexed Array

Indexed arrays work with foreach too. It visits each item in turn, so you can print every value without touching the index numbers:

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