Page 143 - Beginning PHP 5.3
P. 143
Chapter 6: Arrays
If in doubt, always initialize your array variables when you first create them, even if you ’ re not creating
any array elements at that point. You can do this easily by using the array() construct with an empty list:
$authors = array();
This creates an array with no elements (an empty array). You can then go ahead and add elements later:
$authors[] = “Steinbeck”;
$authors[] = “Kafka”;
$authors[] = “Tolkien”;
$authors[] = “Dickens”;
You can also add and change elements of associative arrays using square bracket syntax. Here an
associative array is populated in two ways: first using the array() construct, and second using the
square bracket syntax:
// Creating an associative array using the array() construct
$myBook = array( “title” = > “The Grapes of Wrath”,
“author” = > “John Steinbeck”,
“pubYear” = > 1939 );
// Creating the same array using [] syntax
$myBook = array();
$myBook[“title”] = “The Grapes of Wrath”;
$myBook[“author”] = “John Steinbeck”;
$myBook[“pubYear”] = 1939;
Changing elements of associative arrays works in a similar fashion to indexed arrays:
$myBook[“title”] = “East of Eden”;
$myBook[“pubYear”] = 1952;
Outputting an Entire Array with print_r()
Arrays can get quite complex, as you see later in the chapter, so often you ’ ll find that you want to inspect
an array to see what it contains. You can ’ t just print an array with print() or echo() , like you can with
regular variables, because these functions can work with only one value at a time. However, PHP does
give you a function called print_r() that you can use to output the contents of an array for debugging.
Using print_r() is easy — just pass it the array you want to output:
print_r( $array );
The following example code creates an indexed array and an associative array, then displays both arrays
in a Web page using print_r() . You can see the result in Figure 6-1 .
105
9/21/09 9:00:09 AM
c06.indd 105
c06.indd 105 9/21/09 9:00:09 AM