Home > Article > Backend Development > How to Pass an Array as Arguments to a Function in PHP?
Passing an Array as Arguments, Not an Array
In PHP, there are ways to pass an array as a list of arguments to a function. This can be achieved using the spread operator (...) or call_user_func_array(). Let's explore the methods:
Spread Operator (Introduced in PHP 5.6)
The spread operator, also known as the "splat operator," is a concise and performant way to unpack an array as arguments.
function variadic(...$args) { echo implode(' ', $args); } $array = ['Hello', 'World']; // Splatting the $array variadic(...$array); // Output: 'Hello World'
Note that indexed array items are mapped to arguments based on their position, not keys.
call_user_func_array()
call_user_func_array() is a less efficient but still useful method for passing an array as arguments.
function variadic($arg1, $arg2) { echo $arg1 . ' ' . $arg2; } $array = ['Hello', 'World']; // Using call_user_func_array() call_user_func_array('variadic', $array); // Output: 'Hello World'
In PHP 8, you can leverage named arguments when using the spread operator with associative arrays:
function variadic(string $arg2, string $arg1) { echo $arg1 . ' ' . $arg2; } $array = ['arg2' => 'Hello', 'arg1' => 'World']; variadic(...$array); // Output: 'World Hello'
The spread operator is the recommended method due to its superior performance and convenience.
The above is the detailed content of How to Pass an Array as Arguments to a Function in PHP?. For more information, please follow other related articles on the PHP Chinese website!