Call a PHP Function with Variable Number of Arguments
When dealing with PHP functions that accept a variable number of arguments, the number of parameters passed to the function can be determined based on the length of an array. To achieve this, PHP provides several techniques:
call_user_func_array
If the arguments are stored in an array, the call_user_func_array function can be employed. This function accepts an array as its second parameter, which contains the function arguments.
Example:
function test() { var_dump(func_num_args()); var_dump(func_get_args()); } $params = [ 10, 'glop', 'test', ]; call_user_func_array('test', $params);
This code will output:
int 3 array 0 => int 10 1 => string 'glop' (length=4) 2 => string 'test' (length=4)
for Loop
Another option is to use a for loop to iterate over the array and pass each element as an argument to the function.
Example:
function test($num1, $str1, $str2) { var_dump(func_get_args()); } $params = [ 10, 'glop', 'test', ]; for ($i = 0; $iThis code will output:
array(1) { [0] => int 10 } array(1) { [0] => string 'glop' (length=4) } array(1) { [0] => string 'test' (length=4) }By utilizing these techniques, you can effectively call PHP functions with a variable number of arguments based on the length of an array.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3