Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

php - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...