-1

PHP supports spread operator PHP Spread Syntax in Array Declaration

$ary = [3, 4, 5];
return [1, 2, ...$ary]; // same as [1, 2, 3, 4, 5]

Now I am trying a simple spread operator on 'Object' but it is failing

 $a = ['a' => 1];
 $b = ['b' => 2];
 $c = [...$a, ...$b]; // Expected $c = ['a' => 1, 'b' => 2]

Am I missing something?

Cannot unpack array with string keys

AbsoluteBeginner
  • 2,160
  • 3
  • 11
  • 21
Owen Kelvin
  • 14,054
  • 10
  • 41
  • 74
  • I don't understand why you call this "Object". Apart from that, doesn't the error message already tell you what's up? – Ulrich Eckhardt May 23 '21 at 06:07
  • Dear this functionality will be coming in php 8.1 and so on, right now its not supported. – Muhammad Asif May 23 '21 at 06:31
  • Even the question you linked to specifically addresses this in the answer: _"Caveat: The unpacked array/Traversable can only have integer keys."_ – El_Vanja May 23 '21 at 07:55

1 Answers1

0

php simply does not support that,,, to obtain the expected result you would need to use array_merge

$a = ['a' => 1];
$b = ['b' => 2];
$c = array_merge($a, $b); // this will have $c = ['a' => 1, 'b' => 2]
Sami Akkawi
  • 193
  • 3
  • 9