0

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

3
  • I don't understand why you call this "Object". Apart from that, doesn't the error message already tell you what's up? Commented May 23, 2021 at 6:07
  • Dear this functionality will be coming in php 8.1 and so on, right now its not supported. Commented May 23, 2021 at 6:31
  • Even the question you linked to specifically addresses this in the answer: "Caveat: The unpacked array/Traversable can only have integer keys." Commented May 23, 2021 at 7:55

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.