Page 146 - Beginning PHP 5.3
P. 146
Part II: Learning the Language
In case you ’ re wondering, yes you can use array_slice() with associative arrays. Although associative
arrays don ’ t have numeric indices, PHP does remember the order of the elements in an associative array.
So you can still tell array_slice() to extract, say, the second and third elements of an associative array:
$myBook = array( “title” = > “The Grapes of Wrath”,
“author” = > “John Steinbeck”,
“pubYear” = > 1939 );
$myBookSlice = array_slice( $myBook, 1, 2 );
// Displays “Array ( [author] = > John Steinbeck [pubYear] = > 1939 )”;
print_r( $myBookSlice );
Note that array_slice() does preserve the keys of elements from an associative array.
By the way, if you leave out the third argument to array_slice() , the function extracts all elements
from the start position to the end of the array:
$authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” );
$authorsSlice = array_slice( $authors, 1 );
// Displays “Array ( [0] = > Kafka [1] = > Tolkien [2] = > Dickens )”;
print_r( $authorsSlice );
Earlier you learned that array_slice() doesn ’ t preserve the indices of elements taken from an indexed
array. If you want to preserve the indices, you can pass a fourth argument, true , to array_slice() :
$authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” );
// Displays “Array ( [0] = > Tolkien [1] = > Dickens )”;
print_r( array_slice( $authors, 2, 2 ) );
// Displays “Array ( [2] = > Tolkien [3] = > Dickens )”;
print_r( array_slice( $authors, 2, 2, true ) );
Counting Elements in an Array
How do you find out how many elements are in an array? Easy: you use PHP ’ s handy count() function.
All you need to do is pass the array to count() , and it returns the number of elements as an integer:
$authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” );
$myBook = array( “title” = > “The Grapes of Wrath”,
“author” = > “John Steinbeck”,
“pubYear” = > 1939 );
echo count( $authors ) . “ < br/ > ”; // Displays “4”
echo count( $myBook ) . “ < br/ > ”; // Displays “3”
You might want to use count() to retrieve the last element of an indexed array:
$authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” );
$lastIndex = count( $authors ) - 1;
echo $authors[$lastIndex]; // Displays “Dickens”
108
9/21/09 9:00:10 AM
c06.indd 108 9/21/09 9:00:10 AM
c06.indd 108