PHP Variadic Functions Code Example

Hello devs

In this example, I am going to explain PHP variadic function example with source code. So from this tutorial, you’ll learn about the PHP variadic functions that accept a variable number of arguments.

So let me introduce the PHP variadic function in a brief with an example. Look, the following function defines a method called sum() that returns the sum of two integers:

function sum(int $x, int $y)
    return $x + $y;

echo sum(10, 20); // 30


Now see the variadic function example in PHP. Allowing the sum() function to accept a variable of arguments, you need to use func_get_args() function. The func_num_args() built-in function returns an array that contains all function arguments. For example:

function sum()
    $numbers = func_get_args();
    $total = 0;
    for ($i = 0; $i < count($numbers); $i++) {
        $total += $numbers[$i];

    return $total;
echo sum(10, 20) . '
'; // 30 echo sum(10, 20, 30) . '
'; // 60


Read also: PHP Splat Operator Code Example


Look,  above sum() function we don’t specify any parameter. So here now in this function, you can put as many parameters as you want. So it's work like a splat operator in PHP. Hope it can help you.