Variadic Functions in PHP

Variadic functions can be called with any number of trailing arguments. For example, fmt.Println is a common variadic function.

Here’s a function that will take an arbitrary number of ints as arguments.

<?php
function sum(...$nums) {
    print_r($nums);
    $total = 0;
    foreach ($nums as $num) {
        $total += $num;
    }
    echo " " . $total . "\n";
}

Within the function, the type of $nums is equivalent to array. We can use functions like count($nums) and iterate over it with foreach, etc.

function main() {
    sum(1, 2);
    sum(1, 2, 3);
    
    $nums = [1, 2, 3, 4];
    sum(...$nums);
}

main();

Variadic functions can be called in the usual way with individual arguments.

If you already have multiple args in an array, apply them to a variadic function using ... like this.

$ php variadic-functions.php 
Array ( [0] => 1 [1] => 2 ) 3
Array ( [0] => 1 [1] => 2 [2] => 3 ) 6
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 ) 10

Another key aspect of functions is their ability to form closures, which we’ll look at next.

Next example: Closures.