Friday, June 30, 2006

PHP: Variable length parameters

When you want to write a function that can use any number of parameters/arguments there are 2 ways.

The first uses defaults and appears as if you are using a variable number of arguments. You have to know the maximum number of parameters/arguments, and for each one you must specify a default. This is shown below in the function href1().

The second is the actual way to get a variable number of parameters/arguments from the function. You use func_num_args() which is the number of arguments, and func_get_arg($i) to fetch each argument (where $i is the argument number).

function ahref1($a="these",$b="are",$c="fake",$d="links")
{
$str="";
$str.="<a href='javascript:void(0);'>$a</a><br>\n";
$str.="<a href='javascript:void(0);'>$b</a><br>\n";
$str.="<a href='javascript:void(0);'>$c</a><br>\n";
$str.="<a href='javascript:void(0);'>$d</a><br>\n";
return $str;
}
function ahref2()
{
$str="";
for($i = 0 ; $i < func_num_args(); $i++)
{
$str.="<a href='javascript:void(0);'>";
$str.=func_get_arg($i)."</a><br>\n";
}
return $str;
}


echo ahref1();
echo ahref1('these');
echo ahref1('these','are');
echo ahref1('these','are','fake');
echo ahref1('these','are','fake','links');
echo ahref2('these','are','fake','links');


In each of the function calls above to href1() and href2(), they all produce the same results:

<a href='javascript:void(0);'>these</a><br> 
<a href='javascript:void(0);'>are</a><br>
<a href='javascript:void(0);'>fake</a><br>
<a href='javascript:void(0);'>links</a><br>