The Most Active and Friendliest
Affiliate Marketing Community Online!

“Adavice”/  “1Win

Tip : Functions which take variable number of arguments in php

D

dman_2007

Guest
We can easily create functions which can take variable number of arguments in php by using following three functions : func_num_args, func_get_arg and func_get_args. Following code will demonstrate how to do it :

Code:
<?php
  function test_func()
  {
    echo 'No. of arguments passed ', func_num_args();
    echo '<br />';
    echo 'First argument passed : ', func_get_arg(0), '<br />'; 
    echo 'List of all arguments passed : ';
    print_r(func_get_args());
    echo '<br /><br />';
  }  
  
  test_func(1);
  test_func(1, 2, 3, 4, 5, 6, 7); 
?>

When run the previous code will produce the following output :

No. of arguments passed 1
First argument passed : 1
List of all arguments passed : Array ( [0] => 1 )

No. of arguments passed 7
First argument passed : 1
List of all arguments passed : Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 )
 
Now, lets deiscuss what each the three functions demonstrated in prvious code example do :

1) func_num_args function

This function returns the total number of arguments passed to a user defined function.

2) func_get_args function

This functions returns all the arguments passed to a user defined function in an array.

3) func_get_arg function

This function takes a single argument which specifies the position of argument to return which was passed to the current user defined function. Function argument position is specified starting from 0. It returns the specified argument when successful or FALSE on error.
 
banners
Back