Arrays are complex variables. An array stores a group of values under a single variable name. It is useful for storing related values as a linked list of information. Information in an array can be handled, accessed, and modified easily.

Creating Arrays

The simplest way to create an array is to assign a value to a variable with square brackets ([ ]) at the end of its name. For example, the following statement creates an array called $cities:

$cities[0] = "Phoenix";

At this point, the array named $cities has been created and has only one value.

$cities[1] = "Tucson";
$cities[2] = "Flagstaff";

Now the array $cities contains three values: Phoenix, Tucson, and Flagstaff.

$cities = array("Phoenix","Tucson","Flagstaff");

This statement also creates the same array.

Types of Arrays

There are two types of arrays:

  1. Indexed Array
  2. Associative Array

The difference is in the way the key is specified.

In an indexed array, the keys are numeric and starts with 0, and the values can be any data type.

In an associative array, the keys are not necessarily numeric, and even when they are numeric, not necessarily in any order. So, when you put data into an associative array, you need to specify both the key and the value.

Multi Dimensional Array

There will be times when multi dimensional arrays are needed. These are array of arrays.

Sorting Arrays

One of the most useful features of arrays is that PHP can sort them for you. PHP originally stores array elements in the order in which you create them. If you display the entire array without changing the order, the elements will be displayed in the order in which you created them.

Walking Through An Array

You will often want to do something to every value in an array. You might want to echo each value, store each value in the database, or add some number to each value in the array. Walking through each and every value in an array, in order, is called iteration or traversing.

The foreach statement walks through the array one value at a time.