Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass an array to a php function that accepts an infinite number of arguments, in PHP 5.5 or earlier?

Tags:

php

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?

like image 946
srayner Avatar asked Sep 15 '15 12:09

srayner


People also ask

How many arguments can a PHP function have?

PHP native functions According to the manual, PHP functions may accept up to 12 arguments.

Can we pass array as argument in PHP?

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){ // ... }

Which PHP function can be used to build a function that accept any number of arguments?

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.

How will you passing an argument to a function in PHP?

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.


1 Answers

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

like image 184
Machavity Avatar answered Oct 14 '22 09:10

Machavity