PHP Variadic Functions: Use Unlimited Arguments

php variadic functions

PHP Variadic functions show you a way to handle a variable number of arguments within a function. They are designed to accept a variable number of arguments through the use of the spread operator “…” in the function parameter.

Let’s take a look at the syntax.

Syntax of Variadic Functions

You need to place the ellipsis (…) before the last parameter in the function signature when you declare a variadic function. For example:

function name( ...$param ) {
  // .... Your code here
}

Let’s move to the following section to explain how it works inside functions.

How the Variadic Functions Work in PHP

In PHP, you use three dots (…) before the parameter to define a variadic function. This enables the function to accept an unlimited number of arguments when invoked elsewhere in the code.

Variadic functions work like the built-in func_get_args() function, which gets all the arguments sent to a function.

But the main difference is that variadic functions let you list the arguments in the function’s header. This makes your code shorter and easier to read.

For example.

function mul( $number1, $number2 ) {
     $args = func_get_args();
     print_r($args);
 }
 mul(55, 16);

Here is the output:

Array ( [0] => 55 [1] => 16 )

This implies that func_get_args() captures all the arguments passed into the function when invoked in other sections of the code.

PHP variadic functions do the same job. You put three dots (…) before the parameter to accept any number of arguments.

Here is an example:

function mul( ...$numbers ) { 
   print_r($numbers);
}
mul(55, 16);

It will print the same result as the previous example.

Examples of PHP Variadic Functions

This variadic function concatenates all the provided arguments.

function variadic_func( ...$param ) {
   $string = '';
   if( count( $param ) ) { 
      for( $i=0; $i<count($param); $i++ ) {
         $string .= $param[$i];
         $string .= " ";
      }
   }
 
   return $string;
}
$welcome = variadic_func( "Welcome", "to", "FlatCoding", "Tutorials" );
echo $welcome;

The output:

Welcome to FlatCoding Tutorials

Use the variadic function with a type hint.

function func( Object ...$obj ) {
   print_r( $obj );
}
func([1, 2, 3]);

This produces an error. Here is the output:

Fatal error: Uncaught TypeError: func(): Argument #1 must be of type object.

To address this error, ensure that you pass arguments of the same data type.

$obj = (object) [1, 2, 3];
func($obj);

The output:

Array ( [0] => stdClass Object ( [0] => 1 [1] => 2 [2] => 3 ) ) 

Unpack an array into arguments with the variadic function.

function table( $w, $x, $y, $z ) {
   echo ( ($w + 20 ) - ( $y + $z ) );
}

table(10, ...[20, 30, 40]); // -40

The variadic parameter must be the last parameter in the function; otherwise, an error will occur.

For example:

function table( ...$x, $y ) {
    // ...
}

table(10, 10);

The output:

Fatal error: Only the last parameter can be variadic in index.php

The correct syntax would be as follows:

function table( $y, ...$x ) {
    // ...
}

table(10, 10);

Wrapping Up

Variadic functions in PHP let you take any number of arguments. You put three dots (…) before the parameter. This way, you can pass as many arguments as you want when you call the function.

To prevent fatal errors, the variadic parameter must always be placed at the end of the function parameter list. This ensures that the function can correctly parse the arguments and avoid any errors that may occur.

PHP introduced variadic functions in version 5.6.

In addition to passing individual arguments, you can also unpack an array into a variadic function. For example, you can call a function and pass an array of arguments like this: callback($var, ...['va', 'ca']). This will unpack the array and pass its values as separate arguments to the function.

When you define a variadic function in PHP, the variadic parameter is treated as an array within the function. This means that you can loop through the arguments and perform operations on them as needed.

What is a variadic function in PHP?

A variadic function in PHP lets you accept any number of arguments. You add three dots (…) before the last parameter in the function to do this.

How do you declare a variadic function in PHP?

You declare it by placing three dots (…) before the last parameter in the function signature. For example:
function example( ...$params ) {
   // code here
}

What is the difference between variadic functions and func_get_args()?

Both capture all arguments passed to a function. But variadic functions list the arguments directly in the function header, making the code shorter and easier to read.

Where must the variadic parameter be placed in the function signature?

The variadic parameter must always be the last parameter. Placing it anywhere else causes a fatal error.

How do you pass an array of arguments to a variadic function?

You can unpack an array into arguments using three dots. For example:
table(10, ...[20, 30, 40]);

Similar Reads

PHP mail() Function: A Complete Guide

PHP mail() is a great built-in function for sending an email directly from your script for account confirmations, password resets, or sending notifications.…

PHP Loop: How Loops Work with Examples

A loop in PHP helps you run tasks without repeating the same lines. In this article, you will learn how…

PHP AND (&&) Operator: Usage & Examples

As you are entering into PHP, it would be essential to understand how logical operators work. The PHP AND operator…

PHP $_FILES: How to Upload Files in PHP

The PHP superglobal $_FILES is a very important utility and great for dealing with file uploads on the web. When a user…

PHP Variable Basics: Everything You Need to Know

Think about the PHP variable as little storage boxes holding your data, whether it is a number, a word, or…

PHP array_diff_ukey Function: How it Works with Examples

The PHP array_diff_ukey function compares keys in two or more arrays. It returns the keys from the first array that…

PHP array_diff_assoc: How to Compare Arrays with Keys

Array values may look the same, but keys can differ. The array_diff_assoc in PHP finds differences by both values and…

PHP array_push Function: How it Works with Examples

PHP array_push lets you add one or more values to the end of an array. It appeared to make adding…

PHP array_all Function: How it Works with Examples

PHP 8.4 released a new built-in function, array_all checks to check if all array values meet a condition. It gives…

PHP array_is_list: Check if an Array is a List with Examples

You need the array_is_list function to know if an array works as a list or not in PHP. What is…

Previous Article

PHP Assign Function to Variable - Examples and Explanation

Next Article

PHP Named Arguments vs. Positional Arguments

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.