Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Element unpacking (...)

Unpack array elements into an array literal or pass iterable elements as function arguments.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

[...$first, ...$second]
f(...$arguments)

Unpack array elements into an array literal or pass iterable elements as function arguments. In an array literal integer keys are renumbered and later string keys overwrite earlier ones. In a function call string keys become named arguments, so the names must match parameters when the function has no variadic catch-all. Integer keys supply positional arguments in calls. Unpacking a positional argument after a named one or assigning one parameter twice raises Error. Unpacking string keys inside an array literal has been supported since PHP 8.1.

[...$first, ...$second]
f(...$arguments)
[{"0":"first","mode":"new","1":"second"},"AB"]

Examples

<?php
$a = [7=>'first','mode'=>'old'];
$b = [9=>'second','mode'=>'new'];
function label(string $left, string $right): string { return $left . $right; }
echo json_encode([[...$a, ...$b], label(...['right'=>'B','left'=>'A'])]);

Result

[{"0":"first","mode":"new","1":"second"},"AB"]

Sources