Use PHP's Array Spread Operator for Merging Arrays

Use PHP's Array Spread Operator for Merging Arrays

PHP 7.4 introduced the array spread operator (...), which provides a concise way to unpack arrays.

$fruits = ['apple', 'banana'];
$vegetables = ['carrot', 'tomato'];

$combined = [...$fruits, ...$vegetables, 'kiwi'];

print_r($combined);
// Outputs: Array ( [0] => apple [1] => banana [2] => carrot [3] => tomato [4] => kiwi )

// It's also useful for merging associative arrays
$defaults = ['color' => 'red', 'size' => 'medium'];
$userPreferences = ['size' => 'large'];

$finalPreferences = [...$defaults, ...$userPreferences];

print_r($finalPreferences);
// Outputs: Array ( [color] => red [size] => large )

The spread operator provides a more readable alternative to array_merge() in many cases, especially when working with a mix of indexed and associative arrays.

← Back to Tips List