PHP spread operator

The so called spread operator was introduced in PHP 7.4 and it has rather peculiar usage. Given an array of elements it will take each element and spread it to it’s own placeholder element. E.g. the array:

$b = [4, 5, 6];

can be merged into another array:

$numbers = [1, 2, 3, ...$b];
print_r($numbers);

Which will result in:

Array ( 
[0] => 1 
[1] => 2 
[2] => 3 
[3] => 4 
[4] => 5 
[5] => 6 
) 

What php does is taking each element from the array and placing it into it’s own place in the new array.

It can even be used when passing an array to function/method arguments: For example the following code allows you to pass an array that will be used by PHP as 3 different arguments:

function create_sentence(string $word1, string $word2,string $word3): string
{
    return $word1 . ' ' . $word2 . $word3;
}

$words = ['Hello', 'world', '!'];

echo create_sentence(...$words);

And the result from this will be:

Hello world!

Leave a Reply

Your email address will not be published. Required fields are marked *