When you call mean(96, 93, 97),
func_num_args( ) returns 3. The
first argument is in position 0, so you iterate
from 0 to 2, not
1 to 3. That's
what happens inside the for loop where
$i goes from 0 to less than
$size. As you can see, this is the same logic used
in the first example in which an array was passed. If
you're worried about the potential overhead from
using func_get_arg( ) inside a loop,
don't be. This version is actually faster than the
array passing method.
There is a third version of this function that uses
func_num_args( ) to return an array containing all
the values passed to the function. It ends up looking like hybrid
between the previous two functions:
// find the "average" of a group of numbers
function mean() {
// initialize to avoid warnings
$sum = 0;
// load the arguments into $numbers
$numbers = func_get_args();
// the number of elements in the array
$size = count($numbers);
// iterate through the array and add up the numbers
for ($i = 0; $i < $size; $i++) {
$sum += $numbers[$i];
}
// divide by the amount of numbers
$average = $sum / $size;
// return average
return $average;
}
$mean = mean(96, 93, 97);
Here you have the dual advantages of not needing to place the numbers
inside a temporary array when passing them into mean(
), but inside the function you can continue to treat them
as if you did. Unfortunately, this method is slightly slower than the
first two.