Creating functions that take a variable number of arguments

35 views Asked by At

IN O'reilly Cookbook 3d edition there is an example: (page 165 (189 on e-reader))

<?php

function mean() {
    $sum = 0;

    $size = func_num_args();

    foreach (func_get_args() as $arg) {
        $sum += $arg;

        $average = $sum / $size;

        return $average;
    }
}
$mean = mean(96, 93, 98, 98);
echo $mean;


?>

The mean should be 96,25 but the echo result is 24 ... what am i doing wrong?

The other solution on the page before gives a good result though:

function sean($numbers){
    $sum = 0;
    $size = count($numbers);

    for ($i = 0; $i < $size; $i++) {
        $sum += $numbers[$i];

    }
$average = $sum / $size;

return $average;
}

$test = sean(array(96, 93, 98, 98));
echo $test;
1

There are 1 answers

3
deceze On BEST ANSWER

You're returning in the first iteration of the loop.
You need to average and return after the loop when all values have been summed.