DEV Community

Cover image for Splat Operator in PHP
Kiran Parajuli
Kiran Parajuli

Posted on

10

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. 😎

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay