PHPRO.ORG

The subject of a variable number of arguements passed to a function pops up quite often. Here we show how easy this is with func_num_args(). The trick to achieving this is to the use of the PHP func_num_args function.


<?php

function numArgs()
{
    
/*** the number of args ***/
    
$numargs func_num_args();

    
/*** return the number of args ***/
    
return $numargs;
}

echo 
numArgs('arg1''arg2''arg3'45);

?>

As you can see when you run this code it will print out
5
To get the arguements you can simply use func_get_args(). Lets modify our code a little to see how this works..


<?php

/**
 *
 * Create a HTML list
 *
 * @param variable
 *
 * @return string
 *
 */
function makeList()
{
    
/*** begin list ***/
    
$list '<ul>';

    
/*** put the args into an array ***/
    
$arg_list func_get_args();

    
/*** loop over the array ***/
    
foreach($arg_list as $arg)
    {
        
$list .= "<li>$arg</li>";
    }
    
$list .= '</ul>';

    return 
$list;
}

/*** call the makeList function with a variable number of args ***/
$list makeList('the''cat''sat''on''the''mat');

echo 
$list;

?>

The above code will produce an ordered list of the arguemnts passed to it, regardless of the number. The output will look like this.

  • the
  • cat
  • sat
  • on
  • the
  • mat