Specifications
Occasionally, you might be interested in the key of each element as well as the value. Your
function can, as with MyPrint(), choose to ignore the key and userdata parameter.
For a slightly more complicated example, we will write a function that modifies the values in
the array and requires a parameter. Note that although we are not interested in the key, we need
to accept it in order to accept the third parameter.
function myMultiply(&$value, $key, $factor)
{
$value *= $factor;
}
array_walk(&$array, “myMultiply”, 3);
Here we are defining a function, myMultiply(), that will multiply each element in the array by
a supplied factor. We need to use the optional third parameter to
array_walk() to take a para-
meter to pass to our function and use it as the factor to multiply by. Because we need this para-
meter, we must define our function,
myMultiply(), to take three parameters—an array
element’s value ($value), an array element’s key ($key), and our parameter ($factor). We are
choosing to ignore the key.
A subtle point to note is the way we pass $value. The ampersand (&) before the variable name
in the definition of myMultiply() means that $value will be passed by reference. Passing by
reference allows the function to alter the contents of the array.
We will address passing by reference in more detail in Chapter 5. If you are not familiar with
the term, for now just note that to pass by reference, we place an ampersand before the variable
name.
Counting Elements in an Array: count(), sizeof(), and
array_count_values()
We used the function count() in an earlier example to count the number of elements in an
array of orders. The function
sizeof() has exactly the same purpose. Both these functions
return the number of elements in an array passed to them. You will get a count of one for the
number of elements in a normal scalar variable and 0 if you pass either an empty array or a
variable that has not been set.
The
array_count_values() function is more complex. If you call
array_count_values($array), this function counts how many times each unique value occurs
in the array $array. (This is the set cardinality of the array.) The function returns an associa-
tive array containing a frequency table. This array contains all the unique values from $array
as keys. Each key has a numeric value that tells you how many times the corresponding key
occurs in $array.
Using PHP
P
ART I
90
05 7842 CH03 3/6/01 3:42 PM Page 90