1.9. Using Arrays
Arrays are complex variables. An array stores a group of values under a single variable name. An array is useful for storing related values. For instance, you can store information about a flower (such as variety, color, and cost) in a single array named $flowerinfo. Information in an array can be handled, accessed, and modified easily. For instance, PHP has several methods for sorting an array. The following sections give you the lowdown on arrays.
1.9.1. 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 instance, assuming that you haven't referenced $cities at any earlier point in the script, the following statement creates an array called $cities:
$cities[1] = "Phoenix";
At this point, the array named $cities has been created and has only one value: Phoenix. Next, you use the following statements:
$cities[2] = "Tucson"; $cities[3] = "Flagstaff";
Now the array $cities contains three values: Phoenix, Tucson, and Flagstaff.
An array can be viewed as a list of key/value pairs. Each key/value pair is called an element. To get a particular value, you specify the key in the brackets. In the preceding array, the keys are numbers — 1, 2, and 3. However, you can also use words for keys. For instance, the following statements create an array of state capitals:
$capitals['CA'] = "Sacramento"; $capitals['TX'] = "Austin"; $capitals['OR'] = "Salem";
You can use shortcuts rather than ...
Get PHP & MySQL® Web Development All-in-One Desk Reference for Dummies® now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.