Php Spread Operator Examples
Spread Operator in Function Arguments
Example 1: Using Spread Operator in Function Calls
<?php function sum($a, $b, $c) { return $a + $b + $c; } $numbers = [1, 2, 3]; echo sum(...$numbers); ?>
Output:
6
Spread Operator in Array Expressions with PHP 7.4
Example 2: Merging Arrays
<?php $array1 = [1, 2, 3]; $array2 = [4, 5, 6]; $mergedArray = [...$array1, ...$array2]; print_r($mergedArray); ?>
Output:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )
Example 3: Adding Elements to an Array
<?php $initial = [1, 2, 3]; $extended = [...$initial, 4, 5]; print_r($extended); ?>
Output:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
Combining Arrays Dynamically
Example 4: Combining Multiple Arrays
<?php $arr1 = [1, 2, 3]; $arr2 = [4, 5]; $arr3 = [6, 7, 8]; $combined = [...$arr1, ...$arr2, ...$arr3]; print_r($combined); ?>
Output:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 )
Example 5: Passing an Array to a Variadic Function
<?php function concatenate(...$strings) { return implode(' ', $strings); } $words = ['Hello', 'World', 'from', 'PHP']; echo concatenate(...$words); ?>
Output:
Hello World from PHP
Spread Operator with Traversable Objects
Example 6: Using Spread Operator with Traversable
<?php class NumberGenerator implements IteratorAggregate { private $numbers; public function __construct($numbers) { $this->numbers = $numbers; } public function getIterator() { return new ArrayIterator($this->numbers); } } $generator = new NumberGenerator([1, 2, 3]); $result = [...$generator]; print_r($result); // Output: Array ( [0] => 1 [1] => 2 [2] => 3 ) ?>
HTML <video> element is used to embed video content into a web page. The <audio> tag is su...