12

Let's say I have 3 const arrays:

const A = ["a", "aa", "aaa"];
const B = ["b", "bb"];
const C = ["c"];

I now want to merge / combine those into another const D array without nesting them. How can I do this?

Basically I'm looking for something like array_merge(), but for constants, because as we all know, expressions can't be assigned to constants.


The result I'm looking for is

const D = ["a", "aa", "aaa", "b", "bb", "c"];

which is what

const D = array_merge(A, B, C);

would provide me with, if expressions were allowed for constants.


I've tried

const D = A + B + C;

but that leaves me with just the contents of A in D.


I've also tried

const D = [A, B, C];

but, as expected, this results in an array of arrays [["a", "aa", "aaa"], ["b", "bb"], ["c"]] which isn't what I'm looking for.

2 Answers 2

28

You can use the spread operator for arrays (also known as unpacking) since PHP 7.4 (initial RFC):

const D = [...A, ...B, ...C];

Demo: https://3v4l.org/HOpYH

I don't think there is any (other) way to do this with previous versions.

Sign up to request clarification or add additional context in comments.

1 Comment

Doesn't work with string keys before 8.1
1

Bit late to this question but for those with PHP < 7.4:

If you provide unique keys for each of the initial separate array elements, then array addition works.

Example:

const A = ["a", "aa", "aaa"];
const B = [10 => "b", 11 => "bb"];
const C = [20 => "c"];
const D = A + B + C;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.