๐ŸŽ“ A1Learner
๐Ÿ”
0 of 27 lessons completed

Argument Unpacking

Argument unpacking spreads the values of an array into a call as separate arguments. The spread mark is three dots placed before the array.

An array becomes the argument list

The total function takes three numbers. The call spreads a three value array, and each value lands in its own parameter.

<?php
function total($a, $b, $c) {
  $sum = $a + $b + $c;
  echo $sum . "\n";
}
total(...[1, 2, 3]);

String keys match parameter names

The keys in this array are the parameter names a, b, and c. The values sit out of order in the array, and the names still send each value to the right parameter.

<?php
function total($a, $b, $c) {
  $sum = $a + $b + $c;
  echo $sum . "\n";
}
total(...["b" => 20, "a" => 10, "c" => 30]);

Unpacking inside an array literal

Two small arrays spread into one bigger array here. The later array holds the key b as well, so its value 9 replaces the earlier value 2.

<?php
$first = ["a" => 1, "b" => 2];
$second = ["b" => 9, "c" => 3];
$all = [...$first, ...$second];
print_r($all);

Example

<?php
function settings($theme, $size, $sound) {
  echo $theme . " " . $size . " " . $sound . "\n";
}
$defaults = ["theme" => "light", "size" => "medium", "sound" => "on"];
$changes = ["size" => "large"];
$merged = [...$defaults, ...$changes];
settings(...$merged);

Key points

  • Use three dots before an array in a call to spread its values as arguments.
  • The values land in the parameters in the order they sit in the array.
  • String keys in the spread array match parameter names, so their order does not matter.
  • Three dots inside an array literal spread one array into another array.
  • When two spread arrays share a string key in an array literal, the later value wins.
  • Unpacking builds the argument list from data, so a call does not need one written value per parameter.

In this example, a settings function takes a theme, a size, and a sound flag. The defaults array holds all three values by name, and the changes array holds one new size. The array spread builds a merged array where the new size wins. The call then spreads the merged array, and its string keys send each value to the matching parameter.

Note

The spread mark in a call and the spread mark in an array literal look the same, but one builds arguments and the other builds an array.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does the spread in total(...[1, 2, 3]) do in a call?