PHP Variable Length Parameter

Description

A function with variable-length parameter list can take as many parameters as user want.

Support Functions

We can use three functions to make a function handle variable length parameters.

  • func_num_args()
  • func_get_arg(), and
  • func_get_args()

func_num_args() and func_get_args() take no parameters.

  • func_num_args() gets the number of arguments passed into your function.
  • func_get_arg() gets the value of an individual parameter.
  • func_get_args() returns an array of the parameters that were passed in.

Example

Here's an example:


<?PHP/* www .  j  av a2s . c  om*/
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); 
?>

The code above generates the following result.





















Home »
  PHP Tutorial »
    Language Basic »




PHP Introduction
PHP Operators
PHP Statements
Variable
PHP Function Create
Exception
PHP Class Definition