phparraysmergeconstants

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


Solution

  • 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.