Search code examples
phparraysmysqliprepared-statementbindparam

How can I call a function with a dynamic amount of arguments?


I have an array and I need to pass each element of the array as parameters to a function.

Say:

$var = array("var2","var3","var4");
//Pass each element as a new parameter to a function
call_to_function ($var2, $var3, $var4);

//However, if the number of array element change it can be
$var = array("var2","var3");
call_to_function ($var2,$var3);

The problem here is, how to build dynamic number of parameters and call the function.

Use: PHP Function mysqli_stmt::bind_param, takes multiple parameters. And I need to derive the parameters from an arrray.

Is there any way to do it?


Solution

  • This should work for you:

    First you need to create an array with references to the corresponding variables. You can simply do this with a foreach loop like below:

    foreach($var as $v) {
            $bindValues[] = &$$v; 
    }
    

    After this you can use call_user_func_array() to call the function to bind the variables. Here it depends if you use procedural or OOP style:

    procedural:

    call_user_func_array("mysqli_stmt_bind_param", array_merge([$stmt, $types], $bindValues));
    

    OOP:

    call_user_func_array([$stmt, "bind_param"], array_merge([$types], $bindValues));