views:

186

answers:

3

Hey all, basically, i have an array:

array('a', 'b', 'c');

Now i run it through an array permutation function and the result is:

Array
(
    [0] => Array
        (
            [0] => C
        )

    [1] => Array
        (
            [0] => B
        )

    [2] => Array
        (
            [0] => B
            [1] => C
        )

    [3] => Array
        (
            [0] => C
            [1] => B
        )

    [4] => Array
        (
            [0] => A
        )

    [5] => Array
        (
            [0] => A
            [1] => C
        )

    [6] => Array
        (
            [0] => C
            [1] => A
        )

    [7] => Array
        (
            [0] => A
            [1] => B
        )

    [8] => Array
        (
            [0] => B
            [1] => A
        )

    [9] => Array
        (
            [0] => A
            [1] => B
            [2] => C
        )

    [10] => Array
        (
            [0] => A
            [1] => C
            [2] => B
        )

    [11] => Array
        (
            [0] => B
            [1] => A
            [2] => C
        )

    [12] => Array
        (
            [0] => B
            [1] => C
            [2] => A
        )

    [13] => Array
        (
            [0] => C
            [1] => A
            [2] => B
        )

    [14] => Array
        (
            [0] => C
            [1] => B
            [2] => A
        )

)

Now my question is, how can i clean that array up so that:

array ( C, B )
is the same as
array ( B, C )

and it removes the second array

How would i do that?

EDIT... after some research based on your answers, this is what I came up with:

array_walk($array, 'sort');
$array = array_unique($array);

sort($array); // not necessary
+2  A: 

Just sort the constituent arrays:

foreach ($arrays AS &$arr)
{
   sort($arr);
}

So {"C", "B"} becomes => {"B", "C"}
and {"B", "C"} becomes => {"B", "C"}

which are identical.

Doug T.
After you sort the arrays, you will need to use array_unique() to remove duplicates.http://us.php.net/manual/en/function.array-unique.php
Robert Greiner
Thanks doug and rob, combining what you both said worked perfectly :)
Ozzy
thanks, I recommend hsz's answer though. It is much cleaner.
Doug T.
+2  A: 
array_multisort($array);
array_unique($array);
hsz
did not know about multisort, +1.
Doug T.
Check this now. :)
hsz
+1  A: 

You can also use the pear package Math_Combinatorics.

require_once 'Combinatorics.php';
$combinatorics = new Math_Combinatorics;
$a = array('a', 'b', 'c');

// creating and storing the combinations
for($combinations = array(), $n=1; $n<=count($a); $n++) {
  $combinations = array_merge($combinations, $combinatorics->combinations($a, $n));
}

// test output
foreach($combinations as $c) {
  echo join(', ', $c), "\n";
}

prints

a
b
c
a, b
a, c
b, c
a, b, c
VolkerK