PHP Variable Length Parameter

In this chapter you will learn:

  1. What is Variable Length Parameter
  2. Support Functions
  3. Example - Use variable length parameters

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/* j  a v  a2 s  .  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.

Next chapter...

What you will learn in the next chapter:

  1. What is a reference
  2. Syntax to create reference variable
  3. Reference variable
  4. Syntax for reference parameters
  5. Function Reference Parameters
  6. Example - Reference parameter
Home » PHP Tutorial » PHP Function Create
PHP Function
PHP Function Create
PHP Function Parameter
PHP Function Default Parameters
PHP Variable Length Parameter
PHP Function Reference Parameter
PHP Function Return
PHP Return Reference
PHP Variable Scope in Functions
PHP Global Variables
PHP Recursive Functions
PHP Anonymous Function
PHP static variable