Home >Backend Development >PHP Tutorial >How Can I Pass an Array as Argument List to a PHP Function?
Passing arrays as argument lists in PHP
In PHP, there are multiple ways to pass an array as a list of arguments to a function. One method, introduced in PHP 5.6, is using the variadic function feature with the ... (splat) operator.
To use the splat operator:
function variadic($arg1, $arg2) { echo $arg1 . ' ' . $arg2; } $array = ['Hello', 'World']; variadic(...$array); // Output: 'Hello World'
Indexed array items are mapped to function arguments based on their position, not their keys.
Since PHP8, named arguments allow you to use the named keys of associative arrays with unpacking:
$array = [ 'arg2' => 'Hello', 'arg1' => 'World', ]; variadic(...$array); // Output: 'World Hello'
Another method to pass an array as arguments is by using the call_user_func_array() function:
function my_callback($name, $age) { echo $name . ' is ' . $age . ' years old.'; } $data = ['John', 25]; call_user_func_array('my_callback', $data); // Output: 'John is 25 years old.'
This method accepts an array of values and unpacks them into individual arguments for the function. However, it's slower than the splat operator method.
The above is the detailed content of How Can I Pass an Array as Argument List to a PHP Function?. For more information, please follow other related articles on the PHP Chinese website!