0

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?

Rizier123
  • 58,877
  • 16
  • 101
  • 156
Veer Shrivastav
  • 5,434
  • 11
  • 53
  • 83

3 Answers3

1

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));
Rizier123
  • 58,877
  • 16
  • 101
  • 156
1

You can use eval() to call the function with dynamic number of parameters.

// Construct the parameter string like "$var[0], $var[1], $var[2]"
$param_str = '';
foreach($var as $key => $val) {
    $param_str .= '$var['.$key.'],';
}
$param_str = rtrim($param_str, ',');

eval('call_to_function('.$param_str.');');

Usage of eval() is not considered good practice but if your are sure that your array keys $var are always integer (like in your example default keys) then this should be good to go.

Ulver
  • 905
  • 8
  • 13
-1

call_user_func_array() is just for that:

call_user_func_array(array($stmt, 'bind_param'), $var);
Marek
  • 7,337
  • 1
  • 22
  • 33