0

I have a PHP array like this...

$myarray = array(
'red', 'yellow', 'green, 'blue'
);

Order does not matter to me so I think I am trying to calculate combinations rather than permutations. I am wanting to get this back...

$finalarray = array(
    'Red', 'Green',
    'Red', 'Yellow',
    'Red', 'Blue',
    'Green', 'Yellow',
    'Green', 'Blue',
    'Yellow', 'Blue'
);

Is there a built in PHP feature for achieving this or is there a way to do it with loops?

3

2 Answers 2

2

You can of course with permutation libraries, but that you have to sort every single subarray alphabetically and remove duplicates with array_unique().

Or you might try to be more cost efficient:

$myarray = array(
'red', 'yellow', 'green', 'blue'
);

$result = [];

while ($item = array_pop($myarray)) {
    foreach($myarray as $couple) {
        $result[] = [$item, $couple];
    }
}

print_r($result);

First thing is you are reducing a source array every step, and every context should have its copy of array. It means, that if you are willing to encapsulate mechanics in recursive function to generate more that two member arrays, you need to prevent their internal copies from being changed by anything else than array_pop of their own context.

For the explanation of code above, I'm popping one element off the top of source array, and than iterate over survived element to couple a pair. This way I wont pair "red" with "red", and I wont produce disordered duplicates.

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

Comments

1

This example below

 $myarray = array( 'red', 'yellow', 'green', 'blue' );
 $finalarray = [];
 for ($i = 0; $i < count($myarray); $i++) {
     for ($j = $i + 1; $j < count($myarray); $j++) {
         $finalarray[] = $myarray[$i];
         $finalarray[] = $myarray[$j];
     }
 }
 print_r($finalarray);

will print this

 Array ( [0] => red [1] => yellow [2] => red [3] => green [4] => red [5] => blue [6] => yellow [7] => green [8] => yellow [9] => blue [10] => green [11] => blue )

3 Comments

This one is duplicating results.
In question written that the order does not matter to him, so the code prints the result as the owner want. In example also he had a duplicates.. The logic is here for 1, 2, 3, 4 numbers 1, 2, 1, 3, 1, 4, 2, 3, 2, 4, 3, 4 As I understand, that's what he wanted.
He wanted combinations, not permutations. That's why it is not a duplicate question imo.

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.