typestar

Spread and named arguments in PHP

Modern call sites: pick arguments by name, unpack them from arrays.

<?php
function volume(int $length, int $width, int $height = 1): int {
    return $length * $width * $height;
}

// named arguments skip the defaults you do not care about
echo volume(4, 3, height: 2), "\n";
echo volume(width: 5, length: 2), "\n";

// ...spread unpacks an array into positional arguments
$dims = [3, 4, 5];
echo volume(...$dims), "\n";

function sum(int ...$nums): int {
    return array_sum($nums);
}
echo sum(1, 2, 3, 4), "\n";

How it works

  1. height: 2 targets one parameter by name and skips the rest.
  2. Named arguments can arrive in any order the caller likes.
  3. ...$dims spreads an array across the positional parameters.
  4. In a signature, int ...$nums collects any number of arguments instead.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
438
Tokens
108
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 86 seconds.

Type this snippet

Step 3 of 3 in Functions, step 12 of 27 in Language basics.

← Previous Next →