[ Team LiB ] Previous Section Next Section

Accessing Arrays

So far, you've seen the ways in which you can create and add to arrays. In this section, you will examine some of the tools PHP provides to allow you to acquire information about arrays and access their elements.

Getting the Size of an Array

You can access an element of an array by using its index:


print $user[4]

Because of the flexibility of arrays, however, you won't always know how many elements a particular array contains. That's where the count() function comes into play. count() returns the number of elements in an array. In the following code, we define a numerically indexed array and use count() to access its last element:


$users = array ("Bert", "Sharon", "Betty", "Harry" );
print $users[count($users)-1];

Notice that we subtract one from the value returned by count(). This is because count() returns the number of elements in an array, not the index of the last element.

Although arrays are indexed from zero by default, you can change this. For the sake of clarity and consistency, however, this is not usually advisable.

Although count() gives you the size of an array, you can use it to access the last element in the array only if you are sure that array elements have been added consecutively. For example, say we had initialized the $user array with values at arbitrary indices:


$users[66] = "Bert";
$users[100] = "Sharon";
$users[556] = "betty";
$users[703] = "Harry";

count() would not be of any use in finding the final element. The array still contains only four elements, but there is no element indexed by 3. If you are not certain that your array is consecutively indexed, you can use the end() function to retrieve the final element in the array. end() requires an array as its only argument and returns the given array's last element. The following statement prints the final element in the $users array no matter how it was initialized:


print end($users);



Looping Through an Array

PHP's powerful foreach statement is the best way of looping through each element of an array. In the context of numerically indexed arrays, you would use a foreach statement like this:


foreach( $array as $temp ) {
   //...
}

In this statement $array is the array you want to loop through and $temp is a variable in which you will temporarily store each element.

In the following code, we define a numerically indexed array and use foreach to access each of its elements in turn:


$users = array ("Bert", "Sharon", "Betty", "Harry");
foreach ( $users as $val ) {
  print "$val<br />";
  }

You can see the output from this code fragment in Figure 7.1.

Figure 7.1. Looping through an array.

graphics/07fig01.gif

The value of each element is temporarily placed in the variable $val, which we then print to the browser. If you are moving to PHP from Perl, be aware of a significant difference in the behavior of foreach: Changing the value of the temporary variable in a Perl foreach loop changes the corresponding element in the array. Changing the temporary variable in the preceding example would have no effect on the $users array.

Looping Through an Associative Array

To access both the keys and values of an associative array, you need to alter the use of foreach slightly.

In the context of associative arrays, you would use a foreach statement like this:


foreach( $array as $key=>$value ) {
   //...
}

In this statement $array is the array we are looping through, $key is a variable that temporarily holds each key, and $value is a variable that temporarily holds each value.

Listing 7.2 creates an associative array and accesses each key and value in turn.

Listing 7.2 Looping Through an Associative Array with foreach
 1: <!DOCTYPE html PUBLIC
 2:  "-//W3C//DTD XHTML 1.0 Strict//EN"
 3:  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4: <html>
 5: <head>
 6: <title>Listing 7.2 Using foreach</title>
 7: </head>
 8: <body>
 9: <div>
10: <?php
11: $character = array (
12:       "name" => "bob",
13:       "occupation" => "superhero",
14:       "age" => 30,
15:       "special power" => "x-ray vision"
16:       );
17: foreach ( $character as $key=>$val ) {
18:   print "$key = $val<br />";
19: }
20:
21: ?>
22: </div>
23: </body>
24: </html>

The array is created on line 11, and we use the foreach statement on line 17 to loop through the character array. Each key is placed in a variable called $key, and each value is placed in a variable called $val. They are printed on line 18. You can see the output from Listing 7.2 in Figure 7.2.

Figure 7.2. Looping through an associative array.

graphics/07fig02.gif

Outputting a Multidimensional Array

You can now combine these techniques to output the multidimensional array created in Listing 7.1. Listing 7.3 defines a similar array and uses foreach to loop through each of its elements.

Listing 7.3 Looping Through a Multidimensional Array
 1: <!DOCTYPE html PUBLIC
 2:   "-//W3C//DTD XHTML 1.0 Strict//EN"
 3:   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4: <html>
 5: <head>
 6: <title>Listing 7.3 Looping Through a Multidimensional Array</title>
 7: </head>
 8: <body>
 9: <div>
10: <?php
11: $characters = array (
12:       array (
13:         "name"=> "bob",
14:         "occupation" => "superhero",
15:         "age" => 30,
16:         "specialty" =>"x-ray vision"
17:       ),
18:       array (
19:         "name" => "sally",
20:         "occupation" => "superhero",
21:         "age" => 24,
22:         "specialty" => "superhuman strength"
23:       ),
24:       array (
25:         "name" => "mary",
26:         "occupation" => "arch villain",
27:         "age" => 63,
28:         "specialty" => "nanotechnology"
29:       )
30:     );
31:
32: foreach ( $characters as $val ) {
33:   print "<p>";
34:   foreach ( $val as $key=>$final_val ) {
35:     print "$key: $final_val<br />";
36:   }
37:   print "</p>";
38: }
39:
40: ?>
41: </div>
42: </body>
43: <html>

You can see the output from Listing 7.3 in Figure 7.3. We create two foreach loops (lines 32 and 34). The outer loop on line 32 accesses each element in the numerically indexed array $characters, placing each one in $val. Because $val itself then contains an associative array, we can loop through this on line 34, outputting each of its elements (temporarily stored in $key and $final_val) to the browser.

Figure 7.3. Looping through a multidimensional array.

graphics/07fig03.gif

For this technique to work as expected, we need to ensure in advance that $val will always contain an array. To make this code a little more robust, we could use the function is_array() to test $val. is_array() accepts a variable, returning true if the variable is an array or false otherwise. Alternatively, we could cast the $val variable created on line 29 to an array, thereby ensuring that it is always an array, whatever type it started out as. Here's how:


$val = (array) $val;



Examining Arrays with print_r()

Listing 7.3 demonstrates a way of using foreach loops to access elements in an array. This is fine for working with an array or presenting data neatly. But if you only want a quick peek at an array's contents to debug a script, it seems like a lot of work. The print_r() function accepts any variable and outputs information about the argument's contents and structure. If you pass an array to print_r(), you get a listing of the array's elements. print_r() reports in full on each element and explores all structures (such as objects or arrays) it finds. If you develop scripts of any size or complexity, you will probably become a great friend of the print_r() function.

In Listing 7.4 we test this by passing a cut-down version of the $characters array to print_r().

Listing 7.4 Examining an Array with print_r()
 1: <!DOCTYPE html PUBLIC
 2:  "-//W3C//DTD XHTML 1.0 Strict//EN"
 3:  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4: <html>
 5: <head>
 6: <title>Listing 7.4 Testing the print_r() Function</title>
 7: </head>
 8: <body>
 9: <div>
10: <?php
11: $characters = array (
12:       array (
13:         "name"=> "bob",
14:         "occupation" => "superhero",
15:       ),
16:       array (
17:         "name" => "sally",
18:         "occupation" => "superhero",
19:       )
20:    );
21:
22: print_r( $characters);
23:
24: /*
25: prints:
26: Array
27: (
28:   [0] => Array
29:     (
30:       [name] => bob
31:       [occupation] => superhero
32:     )
33:
34:   [1] => Array
35:     (
36:       [name] => sally
37:       [occupation] => superhero
38:     )
39:
40: )
41: */
42:
43: ?>
44: </div>
45: </body>
46: </html>

We create a cut-down version of the $characters array on line 11 and pass it to the print_r() function on line 22. That effectively ends our script, but we include comments between lines 24 and 43 to show the script's output. Note that you will not see the formatting if you view this script's output in a browser because the line breaks and spacing will be ignored. You can restore the formatting by wrapping your call to print_r() in <pre> tags, like so:


print "<pre>";
print_r( $characters );
print "</pre>";

As of PHP 4.3, you can capture the output from print_r() in a variable rather than printing directly to the browser. print_r() optionally accepts Boolean as a second argument. If this is set to true, print_r() returns its output as a string:


$str = print_r( $characters, true );



    [ Team LiB ] Previous Section Next Section