Dec

20

PHP - Traversing Arrays

December 20, 2007 |

The most common task with arrays is to do something with every element, this task is called traverse arrays. There are many ways to do so, and the one you choose will depend on your data and the task you’re performing.
The foreach Construct
The most common way to loop over elements of an array is to use the foreach construct:

$person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Wilma');
    foreach ($person as $key => $value) {
      echo "Fred's $key is $value\n";
    }
    /* output:
    Fred's name is Fred
    Fred's age is 35
    Fred's wife is Wilma
    */

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 each( ) function is one of those functions, it’s used to loop over the elements of an array. It processes elements according to their internal order. 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.

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

Using a for Loop
If you know that you are dealing with an indexed array, where the keys are consecutive integers beginning at 0, you can use a for loop to count through the indices. The for loop operates on the array itself, not on a copy of the array, and processes elements in key order regardless of their internal order.

$addresses = array('spam@cyberpromo.net', 'abuse@example.com');
    for($i = 0; $i < count($addresses); $i++) {
      $value = $addresses[$i];
      echo "$value\n";
    }
    /* output:
    spam@cyberpromo.net
    abuse@example.com
    */

Calling a Function for Each Array Element
PHP provides a mechanism, array_walk( ), for calling a user-defined function once per element in an array. The function you define takes in two or, optionally, three arguments: the first is the element’s value, the second is the element’s key, and the third is a value supplied to array_walk( ) when it is called.


function print_row($value, $key, $color) {
      print("<tr><td bgcolor=$color>$value</td><td bgcolor=$color>$key</td></tr>\n");
    }
    $person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Wilma');
    echo '<table border=1>';
    array_walk($person, 'print_row', 'lightblue');
    echo '</table>';


Similar Posts

Comments

Name (required)

Email (required)

Website

Speak your mind

Sponsors




Links