Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Merge const arrays to new const array without nesting

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 to expect, this results in an array of arrays [["a", "aa", "aaa"], ["b", "bb"], ["c"]] which isn't what I'm looking for.

like image 995
Tobias Wicker Avatar asked Jan 05 '20 18:01

Tobias Wicker


1 Answers

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.

like image 120
Jeto Avatar answered Nov 14 '22 22:11

Jeto