Roman Toasov Roman Toasov - 17 days ago 9
PHP Question

PHP can i pass array with 2 items to function that needs 2 arguments?

Function needs 2 arguments i got array with 2 items instead any way to modify this array so i can pass to function without need to edit function?

function multiply($varOne, $varTwo) {
return $varOne * $varTwo;
}


echo multiply(5, 3); //15


$myarr = [5,3]; //array

echo multiply($myarr); //Missing argument 2 for multiply()


I got to absolutely have arguments coming in array from external source (cannot change this requirement).

Answer

the php function call_user_func_array() should be what you need.

usage:

function multiply($varOne, $varTwo) {
    return $varOne * $varTwo;
}
echo multiply(5, 3); // 15

$myarr = array(5, 3);
echo call_user_func_array("multiply", $myarr); // 15

The specified function (In this case "multiply") will be called with the arguments in the given array.

Comments