What Are The Three Dots ... or Spread Operator in PHP

What Are The Three Dots (…) or Spread Operator in PHP?

There are many ways to use PHP syntax for function calls and arrays. For instance 3 dots (…), spread operator or spread syntax is a PHP syntax which can be used by objects, arrays and function calls. We can use it differently so let’s see how we can use spread syntax in real time PHP code. Here we have shown the uses of three dots or spread operator in PHP with examples. 

PHP Function Calls 

For function calls in PHP we can use 3 dots for converting arrays into function arguments. We have mentioned an example for this where an array is converted into the values for d, c, b and a.  

let numbers = [ 4, 3, 2, 1 ];

let myFunction = function(d, c, b, a) {

    return d + c + b + a;

}

// Returns 10

myFunction(...numbers);

We can further combine it to other values as well using the same function like before. See the following example in this respect which is also a valid one. 

let numbers = [ 1, 2 ];

// Returns 15 (i.e. 5 + 7 + 1 + 2)

myFunction(5, 7, ...numbers);

We can use the same to call a constructor with new. See this example 

let numbers = [ 2019, 26, 3 ];

let thisDate = new Date(...number);

Merging Arrays

We can merge arrays with spread syntax in PHP as well. We can use two spread syntaxes and merge two different arrays into a new one. This is another way to do it. 

let x = [ 1, 2, 3 ];

let y = [ 4, 5, 6 ];

// Returns [ 1, 2, 3, 4, 5, 6 ]

let newArray = [ ...x, ...y ];

We can also use other values to combine with this and the result will be the same:

let x = [ 1, 2 ];

// Returns [] 4, 5, 1, 2 ]

let newArray = [ 4, 5, ...x ];

Merge Objects

For merging objects we can also use spread syntax. We are using two objects to merge into one with different key/value pairs in this following example:

let obj1 = { name: "John" };

let obj2 = { age: 114 };

// Returns { name: "John", age: 114 }

let newObj = { ...obj1, ...obj2 };

If we are merging two objects and there is a duplicate key, the second object will take precedence and overwrite the first one, as shown below:

let obj1 = { name: "John" };

let obj2 = { name: "Jake" };

// Returns { name: "Jake" }

let newObj = { ...obj1, ...obj2 };

These are the few examples of using spread syntax or three dots in PHP which can be used for functions and arrays etc.