Search code examples
phparraysrecursioncombiners

combine array entries with every other entry


Sorry for the title as it looks like most of the other questions about combining arrays, but I don't know how to write it more specific.

I need a PHP function, which combines the entries of one array (dynamic size from 1 to any) to strings in every possible combination.

Here is an example with 4 entries:

$input = array('e1','e2','e3','e4);

This should be the result:

$result = array(
    0 => 'e1',
    1 => 'e1-e2',
    2 => 'e1-e2-e3',
    3 => 'e1-e2-e3-e4',
    4 => 'e1-e2-e4',
    5 => 'e1-e3',
    6 => 'e1-e3-e4',
    7 => 'e1-e4'
    8 => 'e2',
    9 => 'e2-e3',
   10 => 'e2-e3-e4',
   11 => 'e2-e4',
   12 => 'e3',
   13 => 'e3-e4',
   14 => 'e4'
);

The sorting of the input array is relevant as it affects the output. And as you see, there should be an result like e1-e2 but no e2-e1.

It seems really complicated, as the input array could have any count of entries. I don't even know if there is a mathematical construct or a name which describes such a case.

Has anybody done this before?


Solution

  • You are saying that there might be any number of entries in the array so I'm assuming that you aren't manually inserting the data and there would be some source or code entering the data. Can you describe that? It might be easier to directly store it as per your requirement than having an array and then changing it as per your requirement

    This might be helpful Finding the subsets of an array in PHP