Specifications
the output would appear in a browser as
3
2
1
Using each(), current(), reset(), end(), next(), pos(), and prev(), you can write your
own code to navigate through an array in any order.
Applying Any Function to Each Element in an Array:
array_walk()
Sometimes you might want to work with or modify every element in an array in the same way.
The function array_walk() allows you to do this.
The prototype of
array_walk() is as follows:
int array_walk(array arr, string func, [mixed userdata])
Similar to the way we called usort() earlier, array_walk() expects you to declare a function
of your own.
As you can see, array_walk() takes three parameters. The first, arr, is the array to be
processed. The second, func, is the name of a user-defined function that will be applied to
each element in the array. The third parameter, userdata, is optional. If you use it, it will be
passed through to your function as a parameter. You’ll see how this works in a minute.
A handy user-defined function might be one that displays each element with some specified
formatting.
The following code displays each element on a new line by calling the user-defined function
myPrint() with each element of $array:
function myPrint($value)
{
echo “$value<BR>”;
}
array_walk($array, myPrint);
The function you write needs to have a particular signature. For each element in the array,
array_walk takes the key and value stored in the array, and anything you passed as userdata,
and calls your function like this:
Yourfunction(value, key, userdata)
For most uses, your function will only be using the values in the array. For some, you
might also need to pass a parameter to your function using the parameter userdata.
Using Arrays
C
HAPTER 3
3
USING ARRAYS
89
05 7842 CH03 3/6/01 3:42 PM Page 89