Given this example existing function (presumably written prior to PHP5.6);
function sum()
{
$acc = 0;
foreach (func_get_args() as $n) {
$acc += $n;
}
return $acc;
}
in PHP5.6 we can do this;
$values = array(1, 2, 3);
echo sum(...$values);
Can I pass an array in a similar fashion prior to 5.6?
PHP native functions According to the manual, PHP functions may accept up to 12 arguments.
You can pass an array as an argument. It is copied by value (or COW'd, which essentially means the same to you), so you can array_pop() (and similar) all you like on it and won't affect anything outside. function sendemail($id, $userid){ // ... }
In PHP, we can call the func_num_args() function if we wish to return and output the number of arguments that is provided at any point in the use time of a function. This method returns the number of arguments that are passed to the function.
PHP Function ArgumentsArguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.
PHP uses call_user_func_array to pass variadic arguments in PHP versions prior to 5.6
$values = array(1, 2, 3);
echo call_user_func_array('sum', $values);
You should take note that PHP 5.4 and earlier always passes the array variables as a reference (which is a potential gotcha I ran across back in the day). That methodology has been removed in 5.5 and should not be used as it is deprecated since 5.3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With