As an example, the array could consist of an alphabetically
sorted list of state names, with key 0 representing Alabama, and key 49 representing
Wyoming. Using PHP syntax, this might look like the following:
$states = array(0 => "Alabama", "1" => "Alaska"..."49" => "Wyoming");
Using numerical indexing, you could reference the first state (Alabama) like so:
$states[0]
?– Note Like many programming languages, PHP??™s numerically indexed arrays begin with position 0,
not 1.
An associative key logically bears a direct relation to its corresponding value. Mapping
arrays associatively is particularly convenient when using numerical index values just
doesn??™t make sense. For instance, you might want to create an array that maps state
abbreviations to their names, like this: OH/Ohio, PA/Pennsylvania, and NY/New York.
Using PHP syntax, this might look like the following:
$states = array("OH" => "Ohio", "PA" => "Pennsylvania", "NY" => "New York")
You could then reference Ohio like this:
CHAPTER 5 ?– ARRAYS 129
$states["OH"]
It??™s also possible to create arrays of arrays, known as multidimensional arrays. For
example, you could use a multidimensional array to store U.S. state information.
Using PHP syntax, it might look like this:
$states = array (
"Ohio" => array("population" => "11,353,140", "capital" => "Columbus"),
"Nebraska" => array("population" => "1,711,263", "capital" => "Omaha")
);
You could then reference Ohio??™s population:
$states["Ohio"]["population"]
This would return the following :
11,353,140
Logically you??™ll require a means for traversing arrays.
Pages:
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210