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

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

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&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