Variable parameter counts

int func_num_args ( )

mixed func_get_arg ( int arg_num)

array func_get_args ( )

The printf() function we examined previously is able to take an arbitrary number of parameters. That is, it could take just one parameter, or five, or fifty, or five hundred - it can take as many as are passed into it by the user. This is known as a variable-length parameter list, and it is automatically implemented in your user functions. For example:

<?php
    function some_func($a, $b) {
        $j = 1;
    }

    some_func(1,2,3,4,5,6,7,8);
?>

Here the function some_func() is defined to only take two parameters, $a and $b, but we call it with eight parameters and the script should run without a problem. In that example, 1 will be placed into $a, and 2 will be placed into $b, but what happens to the other parameters?

Coming to your rescue are three functions: func_num_args(), func_get_arg(), and func_get_args(), of which the first and last take no parameters. To get the number of arguments that were passed into your function, call func_num_args() and read its return value. To get the value of an individual parameter, use func_get_arg() and pass in the parameter number you want to retrieve to have its value returned back to you. Finally, func_get_args() returns an array of the parameters that were passed in. Here's an example:

<?php
    function some_func($a, $b) {
        for ($i = 0; $i < func_num_args(); ++$i) {
            $param = func_get_arg($i);
            echo "Received parameter $param.\n";
        }
    }

    function some_other_func($a, $b) {
        $param = func_get_args();
        $param = join(", ", $param);
        echo "Received parameters: $param.\n";
    }

    some_func(1,2,3,4,5,6,7,8);
    some_other_func(1,2,3,4,5,6,7,8);
?>

Using func_num_args() alone you can easily implement function error checking. You can, for example, start off each of your functions by checking to make sure func_num_args() is what you are expecting, and, if not, exit. Once you add func_get_arg() into the mix, however, you should easily be able to create your own functions that work with any number of parameters.

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Variable scope in functions >>

Previous chapter: Default parameters

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.