Spread Operator

Spread Operators are a very useful tool in PHP that basically “unpacks” every element within an array.

Usage:

The most common thing I use it for, is putting nested arrays on the same level by using:

$nestedArray = [
  1 => ['content', 'moreContent', 'evenMoreContent']
  2 => ['content', 'moreContent', 'evenMoreContent']
];
 
$leveledArray = array_merge_recursive(...$nestedArray);
 
// leveledArray now equals
$leveledArray = ['content', 'moreContent', 'evenMoreContent', 'content', 'moreContent', 'evenMoreContent'];

What this does is, merge all the sub-arrays into the top array, for every array within the top array.

I have alot used it for adding an arbitrary amount of same kinds of parameters to a function.

public function initApiSessionWithResponse(Response $response, ?Response ...$optionalResponses): Session
{
    $mockHandler = new MockHandler([
        $this->getMockedLoginResponse(),
        $response,
        ...array_values($optionalResponses),
    ]);
}

Here I can add any amount of optionalResponses like so:

initApiSessionWithResponse($requiredResponse, $optionalResponse, $optionalResonse, $optionalResponse etc...);

Which adds an arbitrary amount of responses to the mock handler, which is great for testing applications that do different amounts of API calls in different functions.