[ Team LiB ] Previous Section Next Section

What Is an Array?

You already know that a variable is a "bucket" in which you can temporarily store a value. By using variables, you can create a script that stores, processes, and outputs different information every time it is run. Unfortunately, you can store only one value at a time in a variable. Arrays are special variables that enable you to overcome this limitation. An array enables you to store as many values as you want in the same variable. Each value is indexed within the array by a number or string. If a variable is a bucket, you can think of an array as a filing cabinet—a single container that can store many discrete items.

Of course, if you have five values to store, you could always define five variables. So, why use an array rather than a variable? First, an array is flexible. It can store two values or two hundred values without the need to define further variables. Second, an array enables you to work easily with all its items. You can loop through each item or pull one out at random. You can sort items numerically, alphabetically, or even according to a system of your own.

Each item in an array is commonly referred to as an element. Each element can be accessed directly via its index. An index to an array element can be either a number or string.

By default, array elements are indexed by numbers, starting at 0. It's important to remember, therefore, that the index of the last element of a sequential numerically indexed array is always one less than the number of elements the array contains.

For example, Table 7.1 shows the elements in an array called users. Notice that the third element has an index of 2.

Table 7.1. The Elements in the users Array

Index Number


Which Element?













Indexing arrays by string can be useful in cases where you need to store both names and values.

PHP provides tools to access and manipulate arrays indexed by both name and number.

    [ Team LiB ] Previous Section Next Section