How to Pass an Array as Arguments to a Function in PHP?

DDD
Release: 2024-11-10 06:03:02
Original
774 people have browsed it

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'
Copy after login

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'
Copy after login

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'
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template