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 XML Parsers: Everything You Need to Know

In PHP, manipulation of XML data can be very critical when most systems' data exchange relies on the format. XML—Extensible…

PHP array_map Function: How to Transform Arrays with Examples

PHP added the array_map() function to help you apply one function to each item in an array. Understand the array_map…

PHP strtolower Function: Convert Strings to Lowercase

Text does not always look the same. One word may appear in lowercase, another in uppercase. You want both to…

PHP Arithmetic Operators: Essential Guide

Perhaps you're new to PHP or sharpening your skills and looking to understand how numbers work within this language under…

PHP filter_var: Understand How to Sanitize Input

PHP didn’t have a way to check or clean user input. Developers used scattered code—some wrote custom checks, others used…

PHP $_SESSION: Secure Your Web Applications in PHP

It’s very important to remember user data for each session when building web applications. This enables a high level of…

PHP array_intersect_uassoc: How it Works with Examples

PHP array_intersect_uassoc checks two or more arrays and returns matches. It compares both the values and the keys with a…

PHP filter_list(): List Available Filters

PHP introduces the filter_list() function to give developers a way to check all available filters in the filter extension. This…

PHP Arrow Functions: Understanding “fn” Syntax

Arrow functions were introduced in PHP 7.4. They offer you a way to write simple operations, such as calculations, filters,…

PHP filter_id Function: How to Retrieve PHP Filter IDs

Before PHP 5.2, there was no built-in filter extension in PHP. You had to manually handle and sanitize input. PHP…

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.