Page 173 - Beginning PHP 5.3
P. 173
Chapter 6: Arrays
Here ’ s an example:
$authors = array( “Steinbeck”, “Kafka” );
$moreAuthors = array( “Tolkien”, “Milton” );
// Displays “Array ( [0] = > Steinbeck [1] = > Kafka [2] = > Tolkien [3] = >
Milton )”
print_r( array_merge( $authors, $moreAuthors ) );
Note that array_merge() joins the array elements of the arrays together to produce the final array. This
contrasts with array_push() , array_unshift() , and the square bracket syntax, which all insert array
arguments as - is to produce multidimensional arrays:
$authors = array( “Steinbeck”, “Kafka” );
$moreAuthors = array( “Tolkien”, “Milton” );
array_push( $authors, $moreAuthors );
// Displays “Array ( [0] = > Steinbeck [1] = > Kafka [2] = > Array ( [0] = >
Tolkien [1] = > Milton ) )”
print_r( $authors );
A nice feature of array_merge() is that it preserves the keys of associative arrays, so you can use it to
add new key/value pairs to an associative array:
$myBook = array( “title” = > “The Grapes of Wrath”,
“author” = > “John Steinbeck”,
“pubYear” = > 1939 );
$myBook = array_merge( $myBook, array( “numPages” = > 464 ) );
// Displays “Array ( [title] = > The Grapes of Wrath [author] = > John
Steinbeck [pubYear] = > 1939 [numPages] = > 464 )”
print_r ( $myBook );
If you add a key/value pair using a string key that already exists in the array, the original element gets
overwritten. This makes array_merge() handy for updating associative arrays:
$myBook = array( “title” = > “The Grapes of Wrath”,
“author” = > “John Steinbeck”,
“pubYear” = > 1939 );
$myBook = array_merge( $myBook, array( “title” = > “East of Eden”, “pubYear”
= > 1952 ) );
// Displays “Array ( [title] = > East of Eden [author] = > John Steinbeck
[pubYear] = > 1952 )”
print_r ( $myBook );
135
9/21/09 9:00:22 AM
c06.indd 135
c06.indd 135 9/21/09 9:00:22 AM