将数组转换为独立的函数参数 - 如何? [英] Turn array into independent function arguments - howto?

查看:21
本文介绍了将数组转换为独立的函数参数 - 如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在函数调用中使用数组中的值作为独立参数.示例:

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}"; }

数组中值的数量未知.

可能的解决方案:

  1. 我可以将数组作为单个参数传递 - 但更愿意作为多个独立的函数参数传递.

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

implode() 将数组转换为逗号分隔的字符串.(失败,因为它只是一个字符串.)

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

使用单个参数:

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

  • 使用eval()?

    遍历数组?

    感谢建议.谢谢.

    推荐答案

    这个问题已经很老了,但最终在 PHP 5.6+ 中得到了更直接的支持:

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

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

    $arr = array("alpha", "beta");
    my_func(...$arr);
    

    这篇关于将数组转换为独立的函数参数 - 如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆