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?
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?
You can use func_get_args() inside your function to parse any number of passed parameters.
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', '.'));
?>
You can use these functions from within your function scope:
Some examples:
foreach (func_get_args() as $arg)
{
// ...
}
for ($i = 0, $total = func_num_args(); $i < $total; $i++)
{
$arg = func_get_arg($i);
}
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.
You will have 3 functions at your disposal to work with this. Have the function declaration like:
function foo()
{
/* Code here */
}
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.