php - How do I pass all elements of an array (of unknown length) to a function as separate parameters? -
this question has answer here:
i have array in php may contain data such this:
$data = array("apples", "oranges", "grapes", "pears"); i want pass these values mysqli bind_param function. example this:
$stmt->bind_param("ssss", $data[0], $data[1], $data[2], $data[3]); my question how can produce same results above if length of array unknown? example may five, ten or 15 elements long.
with php 5.6 or higher:
$stmt->bind_param(str_repeat("s", count($data)), ...$data); with php 5.5 or lower might (and i did) expect following work:
call_user_func_array( array($stmt, "bind_param"), array_merge(array(str_repeat("s", count($data))), $data)); ...but mysqli_stmt::bind_param expects parameters references whereas passes list of values (thanks barmar pointing out).
you can work around (although it's ugly workaround) first creating array of references original array.
$references_to_data = array(); foreach ($data &$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));
Comments
Post a Comment