rfc:spread_operator_for_array

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revisionBoth sides next revision
rfc:spread_operator_for_array [2019/04/05 06:09] jhdxrrfc:spread_operator_for_array [2019/04/05 13:35] – more example jhdxr
Line 22: Line 22:
  
 Spread operator works for both array syntax(''array()'') and short syntax(''[]''). Spread operator works for both array syntax(''array()'') and short syntax(''[]'').
 +
 +It's also possible to unpack array returned by a function immediately.
 +
 <code php> <code php>
 $arr1 = [1, 2, 3]; $arr1 = [1, 2, 3];
Line 27: Line 30:
 $arr3 = [0, ...$arr1]; //[0, 1, 2, 3] $arr3 = [0, ...$arr1]; //[0, 1, 2, 3]
 $arr4 = array(...$arr1, ...$arr2, 111); //[1, 2, 3, 1, 2, 3, 111] $arr4 = array(...$arr1, ...$arr2, 111); //[1, 2, 3, 1, 2, 3, 111]
 +$arr5 = [...$arr1, ...$arr1]; //[1, 2, 3, 1, 2, 3]
 +
 +function getArr() {
 +  return ['a', 'b'];
 +}
 +$arr6 = [...getArr(), 'c']; //['a', 'b', 'c']
 </code> </code>
 +
  
 ==== String keys ==== ==== String keys ====
Line 66: Line 76:
 ==== Advantages over array_merge ==== ==== Advantages over array_merge ====
   - Spread operator should have a better performance than ''array_merge''. It's becuase not only that spread operator is a language structure while ''array_merge'' is a function call, but also compile time optimiztion can be performaned for constant arrays.   - Spread operator should have a better performance than ''array_merge''. It's becuase not only that spread operator is a language structure while ''array_merge'' is a function call, but also compile time optimiztion can be performaned for constant arrays.
-  - ''array_merge'' only supports array, while spread operator also supportes objects implementing ''Traversable''+  - ''array_merge'' only supports array, while spread operator also supportes objects implementing ''Traversable''. 
 +<code php> 
 +// Before 
 +array_merge(iterator_to_array($iter1), iterator_to_array($iter2)) 
 + 
 +// Or to generalise to all iterables 
 +array_merge( is_array($iter1) ? $iter1 : iterator_to_array($iter1), 
 +is_array($iter2) ? $iter2 : iterator_to_array($iter2) ) 
 + 
 +// After (handles both cases) 
 +[ ...$iter1, ...$iter2 ] 
 + 
 +//Thanks Rowan for providing this example 
 +</code>
  
 ==== ... should be preserved for other use (e.g. map concat) ==== ==== ... should be preserved for other use (e.g. map concat) ====
rfc/spread_operator_for_array.txt · Last modified: 2019/05/13 12:45 by nikic