Chapter 5. Arrays

Now that we have a handle on the concept of strings, let’s take a look at the power and flexibility of arrays. Arrays are known as compound data types; all that really means is that they are more complex in structure than simple strings and integers, which are also known as scalar data types. Imagine an array as an egg carton. It carries 12 individual compartments that can house one egg each, yet it travels around as one entity. The compartments can be broken off and made into single egg holders, or holders in any number combination. Additionally, these compartments are not limited to holding only eggs; they can hold rocks, or cookies, or match sticks. Of course, an analogy like this has its limitations—egg cartons cannot easily be expanded and they cannot hold other egg cartons, all of which, we will see, arrays are excellent at doing.

Let’s talk more precisely about arrays. Like egg cartons, arrays have compartments (elements) that hold data. The elements and their respective data always travel together (although you can have an empty element without data) and are known as key/value pairs. So, if we had an array of five elements, each containing a number in the range from 1 to 5, it would look like Table 5-1 (elements start their counting with 0).

Table 5-1. Visual representation of an array with numeric (indexed) keys

Keys

0

1

2

3

4

Values

1

2

3

4

5

Indexed Arrays

Arrays with numerical keys are known as indexed arrays. The keys can also be named with strings, if you prefer, ...

Get PHP: The Good Parts now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.