1

Is there a PHP equivalent to the python func(*[array]) feature to use the array as a series of arguments for the function? I can't seem to find one online.

Example usage in Python:

def f(a,b):
    print(a, b)

f('abc', 'def')
f(*['abc', 'def'])

Outputs

abc def
abc def

Thanks in advance for any help.

EDIT: This is different to this because that question wants to use an array as a parameter, whereas I want to use an array as a series of parameters.

1

2 Answers 2

4

"..." is Argument unpacking, and can be used in the function definition, or the call

<?php
function add($a, $b) {
    return $a + $b;
}

echo add(...[1, 2])."\n";

$a = [1, 2];
echo add(...$a);

Given a ...array() as the function argument, collect the (remaining) arguments from the call into an array variable:

<?php
function sum(...$numbers) {
    $acc = 0;
    foreach ($numbers as $n) {
        $acc += $n;
    }
    return $acc;
}

echo sum(1, 2, 3, 4);
Sign up to request clarification or add additional context in comments.

Comments

2

In PHP < 5.6 that would be call_user_func_array('f', ['abc', 'def']);

In 5.6+, you can do f(...['abc', 'def']); instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.