Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn array into independent function arguments - howto?

I want to use values in an array as independent arguments in a function call. Example:

// Values "a" and "b"
$arr = array("alpha", "beta");
// ... are to be inserted as $a and $b.
my_func($a, $b)
function my_func($a,$b=NULL) { echo "{$a} - {$b}"; }

The number of values in the array are unknown.

Possible solutions:

  1. I can pass the array as a single argument - but would prefer to pass as multiple, independent function arguments.

  2. implode() the array into a comma-separated string. (Fails because it's just one string.)

  3. Using a single parameter:

    $str = "'a','b'";
    function goat($str);  // $str needs to be parsed as two independent values/variables.
    
  4. Use eval()?

  5. Traverse the array?

Suggestions are appreciated. Thanks.

like image 485
Kristoffer Bohmann Avatar asked Sep 23 '09 17:09

Kristoffer Bohmann


People also ask

How do you pass an array as an argument to a function in Javascript?

Method 1: Using the apply() method: The apply() method is used to call a function with the given arguments as an array or array-like object. It contains two parameters. The this value provides a call to the function and the arguments array contains the array of arguments to be passed.

Can a function argument be an array?

arguments is an Array -like object accessible inside functions that contains the values of the arguments passed to that function.

How do you pass an array as parameter for function in react native?

To pass an array as a prop to a component in React, wrap the array in curly braces, e.g. <Books arr={['A', 'B', 'C']} /> . The child component can perform custom logic on the array or use the map() method to render the array's elements. Copied!


2 Answers

This question is fairly old but there is finally more direct support for this in PHP 5.6+:

http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list.new

$arr = array("alpha", "beta");
my_func(...$arr);
like image 101
Jay Paroline Avatar answered Sep 19 '22 13:09

Jay Paroline


if I understand you correctly:

$arr = array("alpha", "beta");
call_user_func_array('my_func', $arr);
like image 32
Valentin Golev Avatar answered Sep 20 '22 13:09

Valentin Golev