A look at the splat operator (...)

Today we are going to look at something that's been missing from PHP for far too long - the ... token, a.k.a. splat operator. The splat operator helps us to convert an array of values to function's arguments.

Let's create a simple class with a method that takes three arguments:

<?php

class Example {

  /**
   * An example function with three integer arguments
   */
  public static function setColor($red, $green, $blue) {
    // Do something here.
  }

}

Now, let's suppose we have an array of three colors: $colors = [255, 0, 0];

How would we pass these values to our method? Well, the most direct approach is to simply pass the values to it directly:

<?php

Example::setColor($color[0], $color[1], $color[2]);

Now, I don't know about you, but I'm not here to manually set all the array values - after all, we have a computer to do that for us and this gets real old real fast. Surely, there must be a better option? Well, there is... kind of. We can call a function and pass arguments to it as an array:

<?php

call_user_func_array(array('Example', 'setColor'), $colors);

Ok, that's a bit better, but it's not pretty and the performance is not exactly stellar either. Do we have another option?

Since PHP 5.6, the answer is yet. We have a new splat operator (...) available that simplifies things for us. What the splat operator does is it takes an array that's been passed to the function as an argument and splits it up into individual argument values. Let's see that in action:

<?php

Example::setColor(...$colors);

Yup, those three dots in front of our array are it. An array passed into the method will automatically be converted to a set of arguments, and what do you know - the performance is up to 5x better than call_user_func_array() in PHP 5.6.

So there you have it, the splat operator. It's awesome, it has an awesome (unofficial) name, use it.

Tags
Comments

Add new comment

Restricted HTML

  • Allowed HTML tags: <em> <strong> <code> <span>
  • Lines and paragraphs break automatically.