DEV Community

Cover image for Splat Operator in PHP
Kiran Parajuli
Kiran Parajuli

Posted on

Splat Operator in PHP

...$str is called a splat operator in PHP (other languages, including Ruby.)

This feature allows you to capture a variable number of arguments to a function, combined with "normal" arguments passed in if you like. It's easiest to see with an example:

<?php

function concatenate($transform, ...$strings) {
  $string = '';
  foreach($strings as $piece) {
    $string .= $piece;
  }
  return($transform($string));
}

echo concatenate("strtoupper", "I'm ", 20 + 2, " years", " old.");
Enter fullscreen mode Exit fullscreen mode

Output

I'M 22 YEARS OLD.
Enter fullscreen mode Exit fullscreen mode

Latest feature

After PHP 5.5.x, arrays and traversable objects can be unpacked into argument lists when calling functions by using the ... operator.

<?php
function add($a, $b, $c) {
    return $a + $b + $c;
}

$operators = [2, 3];
echo add(1, ...$operators);
?>
Enter fullscreen mode Exit fullscreen mode

Output

6
Enter fullscreen mode Exit fullscreen mode

That's cool. 😎

Discussion (0)