Page 145 - Beginning PHP 5.3
P. 145
Chapter 6: Arrays
You can see that print_r() displays the type of the variable it was passed — Array — followed by a
list of all the elements in the array, in the form key => value . The keys (or indices) of the indexed array
are 0 through 3 , and the keys of the associative array are title , author , and pubYear .
By the way, the script wraps < pre > and < /pre > tags around the output from print_r() so that you can
see the formatting properly. Without these tags, the output would appear on a single line when viewed
in a Web page.
You can use print_r() to output pretty much any type of data, not just array variables. For example,
you can use it to output the contents of objects, which you get to work with in Chapter 8 .
If you ’ d rather store the output of print_r() in a string, rather than displaying it in a browser, pass a
second true argument to the function:
$arrayStructure = print_r( $array, true );
echo $arrayStructure; // Displays the contents of $array
Extracting a Range of Elements with array_slice()
Sometimes you want to access more than one array element at a time. For example, if you have an array
containing 100 pending orders from customers, you might want to extract the first ten orders so that you
can process them.
PHP has a built - in function, array_slice() , that you can use to extract a range of elements from an
array. To use it, pass it the array to extract the slice from, followed by the position of the first element in
the range (counting from zero), followed by the number of elements to extract. The function returns a new
array containing copies of the elements you extracted (it doesn ’ t touch the original array). For example:
$authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” );
$authorsSlice = array_slice( $authors, 1, 2 );
// Displays “Array ( [0] = > Kafka [1] = > Tolkien )”
print_r( $authorsSlice );
This example extracts the second and third elements from the $authors array and stores the resulting
array in a new variable, $authorsSlice . The code then uses print_r() to display the slice.
Note that array_slice() doesn ’ t preserve the keys of the original elements, but instead re - indexes the
elements in the new array, starting from zero. So whereas “ Kafka ” has an index of 1 in the $authors
array, it has an index of 0 in the $authorsSlice array.
107
9/21/09 9:00:10 AM
c06.indd 107
c06.indd 107 9/21/09 9:00:10 AM