An array is a variable which can store multiple values.

Each value is stored it its own array element.

Array elements are indexed so they can be easily referenced.

Numeric arrays

Numeric arrays have numeric indexes, starting with zero:

print 'European cities: ' . $city[0] . ' and ' . $city[1];

Numeric arrays in PHP use zero-based counting, which means you start with zero, not one. This can be a source of confusion.

Here is an alternate syntax:

print $x[0];  // Outputs "one"

Here is yet another syntax, using empty braces to automatically assign numeric indexes:

$city = array();
$city[]='London';  // empty squares braces create new array element
$city[]='Paris';   // each time we use [], we create the next element
print 'Japanese city: ' . $city[2];

The above example is useful when your code adds an arbitrary number of elements which you don’t know in advance.

Associative arrays

Associative arrays use text indexes. Example:

print $state['MN'];  // outputs Minnesota

Another way to make associative arrays:

$state = array ('IA'=>'Iowa', 'MN'=>'Minnesota', 'WI'=>'Wisconsin');
print $state['WI'];  // outputs Wisconsin

The above example uses the array assignment operator: =>

See Also