Spread Operator
Last updated onIf working with PHP and looking for easier workarounds concerning arrays and function arguments, the PHP Spread Operator might just become your new best friend. Known to "spread out" elements, this operator can make your code much shorter, more readable, and flexible.
Whether it’s combining arrays, passing multiple arguments into functions, or creating flexible function calls, the PHP spread operator helps abstract these tasks away with much cleaner and more efficient code.
In this article, basic to advanced uses of the PHP Spread Operator are discussed, with ample examples so you can understand different ways it can be used to optimize your projects.
Firstly, let’s understand how to write its syntax.
Understanding the PHP Spread Syntax
It takes three dots (
). Sometimes also called the "splat" operator since it spreads or "splats" elements out individually. It’s particularly useful when you are working with arrays or iterables. ...
You can take any array or iterable and break down the elements into even more individual pieces, allowing you to merge arrays or work with variable-length function arguments.
Here’s the syntax:
$newArray = [...$array1, ...$array2];
The following sections show you how to use this syntax in typical scenarios so that you can better appreciate its versatility and power.
Expanding Arrays with the Spread Operator in PHP
The PHP spread operator can also be useful when you have to unpack an array and add new items to it dynamically.
For example, if you want to take an array, spread out its elements, and at the same time add new ones, the spread operator does this seamlessly:
$array = [1, 2, 3];
$newArray = [...$array, 4, 5, 6];
This example
will contain$newArray
[1, 2, 3, 4, 5, 6]
. The spread operator is a convenient option to use when you need to add new values but do not want to alter your original array.
Merging Arrays Using PHP Spread Operator
The most popular use of the PHP Spread Operator is array merging. Instead of using extra lines of code to perform this operation, a spread operator can handle it all in one line. It also keeps your code clean while making it manageable as the project grows.
Here is an example:
$array1 = [1, 2, 3];
$array2 = [4, 5, 6];
$mergedArray = [...$array1, ...$array2];
This simple line
now bears all elements from $mergedArray
and $array1
in an orderly fashion. This approach is especially useful anytime elements from different data sources are combined, or when dynamic data structures are in place. Moreover, employing the PHP spread operator in this manner will minimize the likelihood of errors that are common when using more complex merging methods.$array2
You probably know that objects in PHP are similar to arrays. Thus, while the spread operator can work for arrays, mostly, an object will not be able to use it unless it implements certain interfaces. Let's go into detail as to why objects might not support the spread operator directly.
Why Objects Cannot Use the PHP Spread Operator
PHP treats arrays and objects differently. An array can be thought of as a simple, ordered list, so extending an array is easy. Objects, however, are complex, with properties and methods not in any particular order, making unpacking them using the spread operator a little tricky. If you try using the spread operator with just an object, PHP will throw an error.
Here's what could happen:
<?php
class Foo {
public $bar = 'Hello';
}
$obj = new Foo();
$arr = ['world'];
$newArr = [...$obj, ...$arr]; // Cannot unpack an object of class Foo
print_r($newArr);
//=> $newArr will cause an error
This would cause a fatal error since PHP can't unpack-objects like it can arrays. If you still want to extract an object's properties into an array, you could use the
function. This would turn the object into an array that you could then unpack as needed. That might look like this:get_object_vars
<?php
class Foo {
public $bar = 'Hello';
}
$obj = new Foo();
$arr1 = get_object_vars($obj);
$arr2 = ['world'];
$newArr = [...$arr1, ...$arr2];
print_r($newArr); // [[bar] => Hello, [0] => world]
This solution combines properties from
and elements from $obj
without problems into $arr2
.$combinedArray
The PHP Spread Operator with References
Another useful feature of the PHP Spread Operator is that it works with references, too. By referencing an array, all changes you make to the new array will take effect on the original one. For example:
$array = [1, 2, 3];
$ref =& $array;
$newArray = [...$ref, 4, 5];
This would allow
to be populated with $newArray
. The most interesting part about it is the fact that when you change [1, 2, 3, 4, 5]
, the changes would reflect in $array
since they share the same reference. Note, however, that you are not allowed to use $newArray
directly inside of the spread operator, as it will result in an error:&
$newArray = [...&$array, 4, 5]; // Error
The output:
Parse error: syntax error, unexpected token “&” in index.php
Below, we will discuss how the spread operator in PHP can ease the task of calling functions with many arguments.
Passing Multiple Arguments with the Spread Operator
An amazing fact about the PHP Spread Operator is that it’s not just about arrays; it works well with function arguments too. If you add the spread operator as a parameter in your function, you'll be able to pass many values as a single array, which PHP will unpack into individual arguments. Here’s an example:
function sum($a, $b, $c) {
return $a + $b + $c;
}
$values = [1, 2, 3];
echo sum(...$values); // Outputs 6
This is especially useful when working with functions that take a variable number of arguments, as it enables you to use arrays as flexible, dynamic inputs. It saves lines of code and, more importantly, makes your functions much easier to both read and use.
Type Hinting with the PHP Spread Operator
Since PHP 8.0, the spread operator became compatible with type hinting, thus giving it an even broader range of use. Type hinting is a way to make a function expect only a specific data type, which saves time from validating its arguments and helps you avoid bugs that pop up when invalid data is passed. Here is how you use type hinting with the Spread Operator:
function addNumbers(int ...$numbers) {
return array_sum($numbers);
}
$nums = [1, 2, 3, 4];
echo addNumbers(...$nums); // Outputs 10
This example
ensures that all elements in addNumbers
are integers. Type hinting with the spread operator is especially valuable in larger projects, as it helps you maintain consistent and predictable data types.$nums
Wrapping Up
The PHP Spread Operator is indeed a powerful feature, allowing flexibility, ease, and efficiency in your code. Whether it is array merging, working with function parameters, or even adding more type safety via type hinting, the spread operator has something for you. From reducing line counts to increasing readability, it makes PHP an even more exciting tool to use.
The PHP Spread Operator is certainly something you'll want to get a handle on when trying to fine-tune your code. Next time you're working with arrays or functions in PHP, don't hesitate to give the spread operator a try and see how it can clean up and speed up your code.
Frequently Asked Questions (FAQs)
What is the PHP spread operator?
How does the PHP spread operator work with arrays?
Can I use the PHP spread operator with objects?
How can the PHP spread operator be used with function arguments?
What does "type hinting" mean with the PHP spread operator?
Can I use references with the PHP spread operator?
Are there any limitations to using the PHP spread operator?