Walking the array

March 29th, 2005. Tagged: PHP certification

The certification guide demonstrates what is probably the fastest (performance-wise) way to go through the elements of an array - using the array_walk() function. The example in the guide is using a callback function to use the elements of the array. But there's more than that.

Using the array_walk() function you can also make use of the keys of that array. And you can also pass to the walking callback function some values you may find appropriate - these are known as "user-defined" parameters.

An example that uses keys and values:
< ?php // here's an array $french_numbers = array('one' => 'une', 'two' => 'deux', 'three' => 'trois');

// the function we're going to call back
function dumpEm($value, $key) {
echo $key . ' - ' . $value . '
';
}

// call array_walk()
array_walk($french_numbers, 'dumpEm');
?>This example will produce:

one - une
two - deux
three - trois

You can see how the keys were also used. Now for the user-defined data you can pass to your callback function. This data can be of any type. Let's take an array as an example.
< ?php // here's an array $french_numbers = array('one' => 'une', 'two' => 'deux', 'three' => 'trois');

// the function we're going to call back
function dumpEm($value, $key, $legend) {
echo $key . '('. $legend['en'] .') - ' . $value . '('. $legend['fr'] .')
';
}

// call array_walk()
array_walk($french_numbers, 'dumpEm', array('en' => 'English', 'fr' => 'Fran?�ais'));
?>
This will produce:

one(English) - une(Fran?�ais)
two(English) - deux(Fran?�ais)
three(English) - trois(Fran?�ais)

Finally, you can change the array values you pass to the callback function. To do so, you need to pass those elements by reference. Note that you cannot do the same on the array keys though.
< ?php // here's an array $french_numbers = array('one' => 'une', 'two' => 'deux', 'three' => 'trois');

// the function we're going to call back
function dumpEm(&$value, &$key) {
$value = ucfirst($value);
$key = ucfirst($key);
echo $key . ' - ' . $value . '
';
}

// call array_walk()
array_walk($french_numbers, 'dumpEm');

print_r($french_numbers);
?>This will give you:

One - Une
Two - Deux
Three - Trois
Array ( [one] => Une [two] => Deux [three] => Trois )

Tell your friends about this post on Facebook and Twitter

Sorry, comments disabled and hidden due to excessive spam.

Meanwhile, hit me up on twitter @stoyanstefanov