Page 172 - Beginning PHP 5.3
P. 172
Part II: Learning the Language
This code removes all the elements from the second position in the array (position 1) to the end
of the array.
Finally, the fourth example demonstrates that you don’t have to pass an array as the fourth argument.
If you only have one element to add — say, a string value — you can just pass the value. This is
because array_splice() automatically casts the fourth argument to an array before using it. So the
string “Orwell” gets converted into an array with a single element (“Orwell”) before being added to
the array:
print_r( array_splice( $authors, 1, 0, “Orwell” ) );
By the way, you’ll have noticed that the script outputs a lot of the more repetitive markup by creating
variables to store snippets of markup ($headingStart, $headingEnd, $rowStart,
$nextCell, $rowEnd). Not only does this make the PHP code more compact and easier to follow,
but it makes it easier to change the markup at a later point if needed.
Note that, when inserting an array, the keys of the inserted elements aren’t preserved; instead they’re
reindexed using numeric keys. So array_splice() isn’t that useful for inserting associative arrays.
For example:
$authors = array( “Steinbeck”, “Kafka”, “Tolkien” );
array_splice( $authors, 1, 0, array( “authorName” => “Milton” ) );
echo “<pre>”;
print_r( $authors );
echo “</pre>”;
This code produces the following result:
Array
(
[0] => Steinbeck
[1] => Milton
[2] => Kafka
[3] => Tolkien
)
Notice how the “Milton” element has had its original key (“authorName”) replaced with a numeric
key (1).
Merging Arrays Together
If you want to join two or more arrays together to produce one big array, you need the array_merge()
function. This function takes one or more arrays as arguments, and returns the merged array. (The
original array(s) are not affected.)
134
9/21/09 9:00:21 AM
c06.indd 134 9/21/09 9:00:21 AM
c06.indd 134