Home >Backend Development >PHP Tutorial >How Can I Pass an Array as Argument List to a PHP Function?

How Can I Pass an Array as Argument List to a PHP Function?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-10 03:40:02952browse

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:

  • Create an array containing the arguments you want to pass.
  • Prepend the array with the ... operator when calling the function.
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn