Page 168 - Beginning PHP 5.3
P. 168
Part II: Learning the Language
By the way, with both array_unshift() and array_push() , if you include an array as one of the
values to add, the array is added to the original array as an element, turning the original array into a
multidimensional array:
$authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” );
$newAuthors = array( “Hardy”, “Melville” );
echo array_push( $authors, $newAuthors ) . “ < br/ > ”; // Displays “5”
/*
Displays:
Array
(
[0] = > Steinbeck
[1] = > Kafka
[2] = > Tolkien
[3] = > Dickens
[4] = > Array
(
[0] = > Hardy
[1] = > Melville
)
)
*/
print “ < pre > ”;
print_r( $authors );
print “ < /pre > ”;
If you instead want to add the elements of the array individually to the original array, use array_
merge() (discussed later in this chapter).
array_pop() is the counterpart to array_shift() ; it removes the last element from an array and
returns the element ’ s value. To use it, pass the array that you want to remove the element from:
$myBook = array( “title” = > “The Grapes of Wrath”,
“author” = > “John Steinbeck”,
“pubYear” = > 1939 );
echo array_pop( $myBook ) . “ < br/ > ”; // Displays “1939”
// Displays “Array ( [title] = > The Grapes of Wrath [author] = > John
Steinbeck )”
print_r( $myBook );
array_push() and array_pop() are handy for creating a last - in, first - out (LIFO) stack of values.
You add new values onto the “ top ” of the stack with array_push() , then retrieve the most recently
added value with array_pop() . Stacks are very useful if you write a lot of recursive code. (Recursion
is covered in Chapter 7 .)
Adding and Removing Elements in the Middle
If you want to do something a bit more involved than add or remove values at the beginning or end of an
array, you need the more powerful array_splice() function. This function is the array equivalent of the
string - manipulation function substr_replace() . (You learned about substr_replace() in Chapter 5 .)
130
9/21/09 9:00:20 AM
c06.indd 130
c06.indd 130 9/21/09 9:00:20 AM