Prev | Current Page 200 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"

..
$state[49] = "Hawaii";
Interestingly, if you intend for the the index value to be numerical and ascending,
you can omit the index value at creation time:
$state[] = "Pennsylvania";
$state[] = "New Jersey";
...
$state[] = "Hawaii";
Creating associative arrays in this fashion is equally trivial except that the key is
always required. The following example creates an array that matches U.S. state
names with their date of entry into the Union:
$state["Delaware"] = "December 7, 1787";
$state["Pennsylvania"] = "December 12, 1787";
$state["New Jersey"] = "December 18, 1787";
...
$state["Hawaii"] = "August 21, 1959";
The array() construct, discussed next, is a functionally identical yet somewhat
more formal means for creating arrays.
Creating Arrays with array()
The array() construct takes as its input zero or more items and returns an array
consisting of these input elements. Its prototype looks like this:
array array([item1 [,item2 ... [,itemN]]])
Here is an example of using array() to create an indexed array:
CHAPTER 5 ?–  ARRAYS 131
$languages = array("English", "Gaelic", "Spanish");
// $languages[0] = "English", $languages[1] = "Gaelic", $languages[2] = "Spanish"
You can also use array() to create an associative array, like this:
$languages = array("Spain" => "Spanish",
"Ireland" => "Gaelic",
"United States" => "English");
// $languages["Spain"] = "Spanish"
// $languages["Ireland"] = "Gaelic"
// $languages["United States"] = "English"
Extracting Arrays with list()
The list() construct is similar to array(), though it??™s used to make simultaneous
variable assignments from values extracted from an array in just one operation.


Pages:
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212