views:

194

answers:

5

In PHP there are functions like unset() that support any number of parameter we throw at them?

So, I want to create a similar function that is capable of accepting any number of parameters and process them all.

Any idea, how to do this?

+2  A: 

You can use func_get_args() inside your function to parse any number of passed parameters.

Peter Anselmo
+10  A: 

In PHP, use the function func_get_args to get all passed arguments.

<?php
function myfunc(){
    $args = func_get_args();
    foreach ($args as $arg)
      echo $arg."/n";
}

myfunc('hello', 'world', '.');
?>

An alternative is to pass an array of variables to your function, so you don't have to work with things like $arg[2]; and instead can use $args['myvar']; or rewmember what order things are passed in. It is also infinitely expandable which means you can add new variables later without having to change what you've already coded.

<?php
function myfunc($args){
    while(list($var, $value)=each($args))
      echo $var.' '.$value."/n";
}

myfunc(array('first'=>'hello', 'second'=>'world', '.'));
?>
Aaron Harun
+6  A: 

You can use these functions from within your function scope:

  • func_get_arg()
  • func_get_args()
  • func_num_args()

Some examples:

foreach (func_get_args() as $arg)
{
    // ...
}

for ($i = 0, $total = func_num_args(); $i < $total; $i++)
{
    $arg = func_get_arg($i);
}
Alix Axel
+1 for mentioning all 3 relevant functions
thomasrutter
+2  A: 

If you intend to do more research on the matter in the future, the term you're looking for is variadic function. The linked Wikipedia article even includes an example for PHP.

Sedate Alien
+1, @sedate, that was pretty helpful link
Starx
+1  A: 

You will have 3 functions at your disposal to work with this. Have the function declaration like:

function foo()
{
    /* Code here */
}

Functions you can use are as follows

func_num_args() Which returns the amount of arguments that have been passed to the array

func_get_arg($index) Which returns the value of the argument at the specified index

func_get_args() Which returns an array of arguments provided.

Xeross