6.5. Creating Functions That Take a Variable Number of Arguments

Problem

You want to define a function that takes a variable number of arguments.

Solution

Pass an array and place the variable arguments inside the array:

// find the "average" of a group of numbers
function mean($numbers) {
    // initialize to avoid warnings
    $sum = 0;

    // 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(array(96, 93, 97));

Discussion

There are two good solutions, depending on your coding style and preferences. The more traditional PHP method is the one described in the Solution. We prefer this method because using arrays in PHP is a frequent activity; therefore, all programmers are familiar with arrays and their behavior.

So, while this method creates some additional overhead, bundling variables is commonplace. It’s done in Recipe 6.5 to create named parameters and in Recipe 6.8 to return more than one value from a function. Also, inside the function, the syntax to access and manipulate the array involves basic commands such as $array[$i] and count($array).

However, this can seem clunky, so PHP provides an alternative and allows you direct access to the argument list:

// find the "average" of a group of numbers function mean() { // initialize to avoid warnings $sum = 0; // ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.