home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Programming PHPProgramming PHPSearch this book

5.7. Traversing Arrays

The most common task with arrays is to do something with every element—for instance, sending mail to each element of an array of addresses, updating each file in an array of filenames, or adding up each element of an array of prices. There are several ways to traverse arrays in PHP, and the one you choose will depend on your data and the task you're performing.

5.7.2. The Iterator Functions

Every PHP array keeps track of the current element you're working with; the pointer to the current element is known as the iterator. PHP has functions to set, move, and reset this iterator. The iterator functions are:

current( )
Returns the element currently pointed at by the iterator

reset( )
Moves the iterator to the first element in the array and returns it

next( )
Moves the iterator to the next element in the array and returns it

prev( )
Moves the iterator to the previous element in the array and returns it

end( )
Moves the iterator to the last element in the array and returns it

each( )
Returns the key and value of the current element as an array and moves the iterator to the next element in the array

key( )
Returns the key of the current element

The each( ) function is used to loop over the elements of an array. It processes elements according to their internal order:

reset($addresses);
while (list($key, $value) = each($addresses)) {
  echo "$key is $value<BR>\n";
}
0 is spam@cyberpromo.net
1 is abuse@example.com

This approach does not make a copy of the array, as foreach does. This is useful for very large arrays when you want to conserve memory.

The iterator functions are useful when you need to consider some parts of the array separately from others. Example 5-1 shows code that builds a table, treating the first index and value in an associative array as table column headings.

Example 5-1. Building a table with the iterator functions

$ages = array('Person'  => 'Age',
              'Fred'    => 35,
              'Barney'  => 30,
              'Tigger'  => 8,
              'Pooh'    => 40);
// start table and print heading
reset($ages);
list($c1, $c2) = each($ages);
echo("<table><tr><th>$c1</th><th>$c2</th></tr>\n");
// print the rest of the values
while (list($c1,$c2) = each($ages)) {
  echo("<tr><td>$c1</td><td>$c2</td></tr>\n");
}
// end the table
echo("</table>");
<table><tr><th>Person</th><th>Age</th></tr>
<tr><td>Fred</td><td>35</td></tr>
<tr><td>Barney</td><td>30</td></tr>
<tr><td>Tigger</td><td>8</td></tr>
<tr><td>Pooh</td><td>40</td></tr>
</table>

5.7.6. Searching for Values

The in_array( ) function returns true or false, depending on whether the first argument is an element in the array given as the second argument:

if (in_array(to_find, array [, strict])) { ... }

If the optional third argument is true, the types of to_find and the value in the array must match. The default is to not check the types.

Here's a simple example:

$addresses = array('spam@cyberpromo.net', 'abuse@example.com',
                   'root@example.com');
$got_spam = in_array('spam@cyberpromo.net', $addresses);   // $got_spam is true
$got_milk = in_array('milk@tucows.com', $addresses);       // $got_milk is false

PHP automatically indexes the values in arrays, so in_array( ) is much faster than a loop that checks every value to find the one you want.

Example 5-2 checks whether the user has entered information in all the required fields in a form.

Example 5-2. Searching an array

<?php
 function have_required($array , $required_fields) {
   foreach($required_fields as $field) {
     if(empty($array[$field])) return false;
   }
  
   return true;
 }

 if($submitted) {
   echo '<p>You ';
   echo have_required($_POST, array('name', 'email_address')) ? 'did' : 'did not';
   echo ' have all the required fields.</p>';
 }
?>
<form action="<?= $PHP_SELF; ?>" method="POST">
  <p>
    Name: <input type="text" name="name" /><br />
    Email address: <input type="text" name="email_address" /><br />
    Age (optional): <input type="text" name="age" />
  </p>
  
  <p align="center">
    <input type="submit" value="submit" name="submitted" />
  </p>
</form>

A variation on in_array( ) is the array_search( ) function. While in_array( ) returns true if the value is found, array_search( ) returns the key of the found element:

$person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Wilma');
$k = array_search($person, 'Wilma');
echo("Fred's $k is Wilma\n");
Fred's wife is Wilma

The array_search( ) function also takes the optional third strict argument, which requires the types of the value being searched for and the value in the array to match.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.