PHP Variadic Functions

In PHP, you can define functions that accept a variable number of arguments using what's called "variadic functions". These functions allow you to pass an arbitrary number of arguments to them. This can be very useful in situations where you want a function to be flexible and handle different numbers of inputs.

To create a function that accepts a variable number of arguments, you use an ellipsis (. . .) before the last parameter in the function declaration. This parameter will then become an array that contains all the additional arguments passed to the function.

Sum of Numbers

  • This function is named sum and it takes any number of arguments (integers or floats).
  • The . . . $numbers syntax collects all arguments into the $numbers array.
  • It then iterates through the array, adding up each number.
  • The total is returned.

 
function sum(...$numbers)
{
    $total = 0;
    foreach ($numbers as $number) {
        $total += $number;
    }
    return $total;
}
 

In this example,  format_message() is a variadic function that accepts a format string ($format) and any number of additional arguments (...$args). It uses sprintf() to format the message using the provided arguments.

In the first example usage, format_message('Hello %s!', 'John') calls the function with one format specifier %s and one argument 'John'. The function will return 'Hello John!'.

In the second example, format_message('Sum of %d and %d is %d', 10, 20, 10 + 20) uses three format specifiers %d and three arguments 10, 20, and 10 + 20. The function will return 'Sum of 10 and 20 is 30'.

This way, you can create flexible functions that can handle different numbers of arguments and format them using sprintf().

 
function format_message($format, ...$args)
{
    // $format is the first argument, and ...$args captures the rest
    
    // Use sprintf to format the message
    $message = sprintf($format, ...$args);
    
    return $message;
}
 
// Example usage
$message1 = format_message('Hello %s!', 'John');
$message2 = format_message('Sum of %d and %d is %d', 10, 20, 10 + 20);
echo $message1 . "\n"; // Output: Hello John!
echo $message2 . "\n"; // Output: Sum of 10 and 20 is 30

Remember that the variadic parameter must be the last parameter in the function declaration. Additionally, you can mix variadic parameters with regular parameters, but the variadic parameter must always come last.