Skip to main content

PHP Arrays

Think of a PHP array as one variable with room for many values. Everything sits together under a single name, and you reach an individual value through its position number or through a name you gave it.

Array Example

Here $cars keeps three car names in one place, and count() reports how many there are:

Prompt
Write a PHP script that creates an array of three car brand names and stores it in a variable.
Output: PHP script

PHP Array Types

PHP gives you three kinds of arrays, and the difference lies in how you reach the items:

  • Indexed arrays - each item is found by a number
  • Associative arrays - each item is found by a key you name yourself
  • Multidimensional arrays - the items are themselves arrays, one or several

PHP Array Items

PHP does not restrict what you can put in an array. Strings and numbers are what you will see most often, yet an item could just as well be an object, a function or another array.

The types can also be mixed freely within one array.

Mixed Data Types

This array holds a string, an integer and a nested array side by side:

Prompt
Write a PHP script that creates an array containing a string, an integer, and another array as its items.
Output: PHP script

PHP Array Functions

Much of the power of PHP arrays comes from the functions built into the language for working with them.

One of the simplest is count(), which tells you how many items an array holds:

Every array function is documented in our PHP Array Reference.

Count Array Items

Find out how many items $cars contains:

Prompt
Write a PHP script that creates an array of three car brand names and uses the count function to print the number of items.
Output: PHP script