If you’ve used printf/sprintf/etc. in PHP you may be wondering how these functions can accept any number of arguments and still make sense of it. You also may wonder how you can make functions that employ this ‘trick’. Well it’s not a trick really, it seems to be built in to every function the user defines.

function play(){
	$args = func_get_args();
    foreach ($args as $k => $v) {
        echo "act ".($k+1).": $v <br />n";
    }
}
play("intro", "the hunt", "the wedding", "the tragedy", "the finale", "the end");

It prints the arguments even though they are not defined. Is it only with functions with no defined arguments? No. What happens when we define arguments as well.

function play($act_1, $act_2){
	$args = func_get_args();
	echo "Act 1 will be $act_1 ... <br /><br />n";
    foreach ($args as $k => $v) {
        echo "act ".($k+1).": $v <br />n";
    }
}
play("intro", "the hunt", "the wedding", "the tragedy", "the finale", "the end");

It will just print the same as before for each act. That means defining arguments has virtually no effect on the function func_get_args().

Ever tried giving say, substr() 6 arguments though…

Warning: substr() expects at most 3 parameters, 6 given in C:propEasyPHPwwwbwordsmiscunlimited_arguments.php on line 16

That means that built in functions thrrow errors in that situation, while user created ones don’t. It’s not a critical component of PHP programming but it helps to know what will happen

function play($act_1, $act_2){
	echo func_num_args();  //echoes 6
}
play("intro", "the hunt", "the wedding", "the tragedy", "the finale", "the end");

If you try the above code you will see that func_num_args() return the number of arguments the user entered not the number of defined arguments, which is intentional. func_get_arg($arg_num) simply returns the function with the index entered. The first is 0 for example. That’s the important stuff when dealing with argument lists.