Current Location: Home> Latest Articles> PHP Function Arguments with “...” Explained with Examples

PHP Function Arguments with “...” Explained with Examples

M66 2025-10-15

Understanding the Ellipsis (...) in PHP Function Parameters

In PHP development, we often need to write functions that accept a variable number of arguments. To handle this, PHP provides a simple syntax: placing three dots (...) before a parameter allows the function to accept a variable-length argument list. This feature makes it easy to process different numbers of arguments without having to define a fixed set of parameters.

Defining Functions with Variable Arguments Using “...”

Here’s a simple example of defining a function that can accept any number of arguments:

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

// Test the add() function
echo add(1, 2, 3, 4, 5); // Output: 15
echo add(10, 20, 30);   // Output: 60

In this example, the add() function uses the ellipsis (...) to declare a variable parameter $numbers. PHP automatically packs all passed arguments into an array, allowing the function to iterate through and calculate the sum easily.

Handling Variable Arguments with func_get_args() and func_num_args()

Besides the ellipsis syntax, PHP provides two functions for similar functionality:

Here’s an example of using these functions:

function printArgs() {
    $numArgs = func_num_args();
    $args = func_get_args();

    echo "Number of arguments: {$numArgs}\n";

    foreach ($args as $index => $arg) {
        echo "Argument {$index}: {$arg}\n";
    }
}

// Test the printArgs() function
printArgs('apple', 'banana', 'cherry', 'date');

With this method, you can dynamically handle any number of arguments. Compared to the ellipsis syntax, this approach is useful when you cannot modify the function’s parameter definition directly.

Conclusion

Using the ellipsis (...) or the func_get_args() family of functions allows PHP functions to be more flexible and versatile. Whether writing utility functions or implementing framework-level logic, these features help improve code scalability and maintainability.

By understanding and properly using PHP’s variable argument features, developers can write cleaner and more efficient code, offering flexible solutions for various project requirements.