Pavel S.
Pavel S.

Reputation: 12332

PHP - Pass array as variable-length argument list

I have really simple problem in my PHP script. There is a function defined which takes variable length argument list:

function foo() {
  // func_get_args() and similar stuff here
}

When I call it like this, it works just fine:

foo("hello", "world");

However, I have my variables in the array and I need to pass them "separately" as single arguments to the function. For example:

$my_args = array("hello", "world");
foo(do_some_stuff($my_args));

Is there any do_some_stuff function which splits the arguments for me so I can pass them to the function?

Upvotes: 13

Views: 10430

Answers (8)

Morten Haggren
Morten Haggren

Reputation: 66

I know it's an old question but it still comes up as the first search result - so here is an easier way;

<?php
function add(... $numbers) {
    $result=0;
    foreach($numbers as $number){
      $result+=intval($number);
    }
    return $result;
}

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

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

Source: https://www.php.net/manual/en/functions.arguments.php#example-142

Upvotes: 0

Pheonix
Pheonix

Reputation: 6052

This solution is not recommended at all, but just showing a possibility :

Using eval

eval ( "foo('" . implode("', '", $args_array) . "' )" );

Upvotes: -1

lorenzo-s
lorenzo-s

Reputation: 17010

You are searching for call_user_func_array().

https://www.php.net/manual/en/function.call-user-func-array.php

Usage:

$my_args = array("hello", "world");
call_user_func_array('foo', $my_args);

// Equivalent to:
foo("hello", "world");

Upvotes: 3

Arjan
Arjan

Reputation: 9874

If you can change the code of foo() it should be easy to solve this in just one place.

function foo()
{
    $args = func_get_args();
    if(count($args) == 1 && is_array($args[0]))
    {
        $args = $args[0]
    }
    // use $args as normal
}

Upvotes: 0

dfsq
dfsq

Reputation: 193271

Well you need call_user_func_array

call_user_func_array('foo', $my_args);

http://php.net/manual/en/function.call-user-func-array.php

Upvotes: 6

Peter O&#39;Callaghan
Peter O&#39;Callaghan

Reputation: 6186

Sounds to me like you are looking for call_user_func_array.

Upvotes: 3

Related Questions