如何将数组的所有元素(未知长度)作为单独的参数传递给函数? [重复]

如何将数组的所有元素(未知长度)作为单独的参数传递给函数?  [重复]

问题描述:

This question already has an answer here:

I have an array in PHP which may contain data such as this:

$data = array("Apples", "Oranges", "Grapes", "Pears");

I then want to pass these values into the mysqli bind_param function. For this example it would look like this:

$stmt->bind_param("ssss", $data[0], $data[1], $data[2], $data[3]);

My question is how can I produce the same results as above if the length of the array is unknown? For example it may be five, ten or 15 elements long.

</div>

此问题已经存在 这里有一个答案: p>

  • 如何在PHP中动态绑定mysqli bind_param参数? 6 answers span> li> ul> div>

    我在PHP中有一个可能包含数据的数组 例如: p>

      $ data = array(“Apples”,“Oranges”,“Grapes”,“Pears”); 
      code>  pre>  
     
     

    然后我想将这些值传递给 mysqli code> bind_param code>函数。 对于此示例,它将如下所示: p>

      $ stmt-&gt; bind_param(“ssss”,$ data [0],$ data [1],$ data [2  ],$ data [3]); 
      code>  pre> 
     
     

    我的问题是,如果数组的长度未知,我怎样才能产生与上面相同的结果? 例如,它可能是5个,10个或15个元素。 p> div>

With PHP 5.6 or higher:

$stmt->bind_param(str_repeat("s", count($data)), ...$data);

With PHP 5.5 or lower you might (and I did) expect the following to work:

call_user_func_array(
    array($stmt, "bind_param"),
    array_merge(array(str_repeat("s", count($data))), $data));

...but mysqli_stmt::bind_param expects its parameters to be references whereas this passes a list of values (thanks Barmar for pointing this out).

You can work around this (although it's an ugly workaround) by first creating an array of references to the original array.

$references_to_data = array();
foreach ($data as &$reference) { $references_to_data[] = &$reference; }
unset($reference);
call_user_func_array(
    array($stmt, "bind_param"),
    array_merge(array(str_repeat("s", count($data))), $references_to_data));