Scalax
Scalax

Reputation: 430

Ordered combinations without repetition in php?

i have the following array:

Array("one", "two", "three", "four");

and i need a function that outputs all the ordered combinations of the array elements without repetition. The output should be

one
one two
one two three
one two three four
two
two three
two three four
three
three four
four

The output should not include:

one one
one two four
two one three
four two three

And so on ...

Does anybody of you have already implemented this kind of alghoritm?

Upvotes: 0

Views: 5076

Answers (1)

Passerby
Passerby

Reputation: 10070

This would simply be two nested loops:

Online demo

function permutation(array $arr)
{
    while($ele=array_shift($arr))
    {
        $x=$ele;
        echo $x."\n";
        foreach($arr as $rest)
        {
            $x.=" $rest";
            echo $x."\n";
        }
    }
}
permutation(array("one","two","three","four"));

Upvotes: 2

Related Questions