Variadic Functions in PHP

Variadic functions, also known as variable argument functions, are a very useful feature in PHP that allows you to define functions by accepting an arbitrary number of arguments. This feature was introduced in the PHP 5.6 version.

Variadic functions are especially useful when you want to define a function that can handle any number of arguments without the need to explicitly define every parameter in advance.

In simple words, they are useful in such scenarios where the number of arguments to a function is not known in advance.

Syntax of Variadic Functions in PHP


You can define a variadic function in PHP by just putting the splat operator (…) before the name of last parameter in the function declaration. The general syntax to define a variadic function is as follows:

function functionName($fixedParam, ...$variadicParam) {
   // Function body
}

In the above syntax of variadic function, $fixedParam represents fixed parameters that are required. The last parameter …$variadicParam captures all additional arguments as an array passed to the function. However, a variadic function can accept zero, one, or many arguments.

Basic Examples on Variadic Functions


Let’s take some basic examples based on variadic functions in PHP.

Example 1:

<?php
function sumNumbers(...$numbers) {
   return array_sum($numbers);
}
echo sumNumbers(1, 2, 3, 4);
?>
Output:
      10

In this example, we have defined a variadic function named sumNumbers() that accepts a variable number of arguments. When we call this function with passing four numeric arguments, this function accepts these arguments and returns the sum of arguments. The array_sum() function calculates the sun of arguments.


Example 2:

<?php
function myVarFunc(...$args) {
  foreach($args as $arg) {
     echo $arg . "\n";
  }
}
myVarFunc("Java", "Python", "PHP");
?>
Output:
       Java
       Python
       PHP

In this example, we have defined a function named myVarFunc() that accepts an arbitrary number of arguments. When we have called this function with passing three argument values, the function displays each of those arguments on a new line.

Variadic Functions with Type Declarations


Now, PHP allows you to specify types for variadic parameters. This means that you can now pass all arguments to be of a certain type to the variadic function. Let’s take an example on it.

Example 3:

<?php
function multiplyNumbers(int ...$numbers): int {
   return array_product($numbers);
}
echo multiplyNumbers(2, 3, 4, 5);
?>
Output:
      120

In this example, the parameter int …$numbers inside the parentheses of a function will accept all arguments of integer type. If you pass the argument values of other types, you will have an undefined type error. The array_product function calculates the product of the numbers and returns the result to the function caller.

Using with Arrays


You can also pass an array of arguments to a variadic function when calling it. Look at the below example.


Example 5:

<?php
function printColors(...$colors) {
   foreach ($colors as $color) {
      echo "$color \n";
   }
}
// Define an array.
$colorArray = ["Red", "Green", "Blue", "Blue"];
printColors(...$colorArray); // Calling function.
?>
Output:
      Red 
      Green 
      Blue 
      Blue 

Fixed and Variadic Parameters


You can also define a variadic function with fixed parameters along with variadic ones. The fixed parameters must come before the variadic parameter.

Example 6:

<?php
function greetUsers($greeting, ...$names) {
  foreach ($names as $name) {
    echo "$greeting, $name!\n";
  }
}
greetUsers("Hello", "Alice", "Bob", "Charlie", "Saanvi");
?>
Output:
      Hello, Alice!
      Hello, Bob!
      Hello, Charlie!
      Hello, Saanvi!

In this example, we have passed an argument “Hello” to the fixed parameter named $greeting and rest arguments to the variadic parameters.

Example 7:

<?php
function createUser($role, ...$details) {
   $user = [
      'role' => $role,
      'details' => $details
   ];
   return $user;
}
print_r(createUser('admin', 'John Doe', 'john@example.com', 25));
?>
Output:
    Array
    (
        [role] => admin
        [details] => Array
        (
            [0] => John Doe
            [1] => john@example.com
            [2] => 25
        )

    )

In this tutorial, you have learned about variadic functions in PHP that is a powerful feature to handle variable-length arguments. Next, we will learn about strict typing in PHP.