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

Understanding the PHP Exclusive OR (XOR) Operator

In PHP, there is this interesting operator known as "exclusive OR," or just XOR. It is somewhat of an underdog…

PHP $_COOKIE: Securely Store and Manage Data

Ever notice how some websites just seem to "know" you? That’s thanks to cookies! When you’re working with PHP, $_COOKIE becomes a…

PHP $_REQUEST: Learn How to Capture User Inputs

Today, we will discuss the most prominent and useful superglobal in PHP, $_REQUEST, to get user input. The $_REQUEST array lets you retrieve…

PHP if-elseif Statement: ‘elseif’ versus ‘else if’

PHP’s if-elseif statement is a fundamental construct that allows developers to control the flow of their code based on different conditions. In…

How to Connect PHP to MongoDB

Connecting PHP to MongoDB allows you to integrate database functionalities into your web applications. MongoDB is a NoSQL database that…

How to Create Table in MySQL with PHP?

One of the first tasks you will likely encounter is creating a table in databases. Tables are the main part…

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…

Concatenating Strings in PHP: Tips and Examples

In PHP, string operators, such as the concatenation operator (.) and its assignment variant (.=), are employed for manipulating and…

PHP XML Expat Parser: A Complete Guide

If you've ever tried to pull data from an XML file, you know it can be a bit tricky at…

PHP Predefined Constants Explained Simply

PHP has a number of predefined constants that give you some information about the language and its environment. You can…

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.