Skip to content

PHP Tutorial Functions

Variadic Functions

Lesson 109 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

Sometimes you do not know how many arguments a function will receive. A variadic function collects them all into an array. You write three dots before the parameter.

index.php
PHP
<?php
function sum(int ...$numbers): int
{
    return array_sum($numbers);
}

echo sum(1, 2, 3) . "\n";
echo sum(10, 20, 30, 40) . "\n";
echo sum();
Output
OUTPUT
6
100
0

Inside the function, $numbers is a normal array of the values.

Typed variadics

The type applies to every item. int ...$numbers accepts only integers.

Required first, extras after

A variadic parameter must be last. Put the required ones before it.

index.php
PHP
<?php
function logMessage(string $level, string ...$parts): string
{
    return "[$level] " . implode(" ", $parts);
}

echo logMessage("INFO", "User", "logged", "in");
Output
OUTPUT
[INFO] User logged in

Spreading an array into arguments

The same three dots work in a call. They unpack an array into separate arguments.

index.php
PHP
<?php
function add(int $a, int $b, int $c): int
{
    return $a + $b + $c;
}

$values = [1, 2, 3];

echo add(...$values);
Output
OUTPUT
6

Merge arrays with the spread operator

index.php
PHP
<?php
$first = ["a", "b"];
$second = ["c", "d"];

print_r([...$first, ...$second]);
Output
OUTPUT
Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
)

String keys become named arguments

Since PHP 8.1, an array with string keys can be spread into named arguments.

index.php
PHP
<?php
function createUser(string $name, int $age): string
{
    return "$name is $age";
}

$data = ["age" => 30, "name" => "Ravi"];

echo createUser(...$data);
Output
OUTPUT
Ravi is 30

The old way: func_get_args()

Before variadic parameters, code used func_get_args() inside the function. You may see it in older projects.

index.php
PHP
<?php
function oldSum()
{
    return array_sum(func_get_args());
}

echo oldSum(1, 2, 3);
Output
OUTPUT
6

Use ...$args in new code. It is clearer and supports types.

lightbulb
A real use
printf(), max() and array_merge() are all variadic. When you write a helper that “takes some values”, a variadic is usually the right shape.