Stecy Aulia
Stecy Aulia

Reputation: 65

Push Array value to every other Array value?

I am not so sure how to explain my problem.

I have Array like this

$foo = array{"one", "two", "three"}

and i need to push every value to other value.

need result kind like this ...

$new = array{"one two three", "one two", "one three", "two three", "one", "two", "three"}

IS that posible to make result like that ?

I hope somebody can help me.

Thanks before :)

Upvotes: 0

Views: 158

Answers (2)

Russell Dias
Russell Dias

Reputation: 73392

Here is a rather simplistic attempt at your problem.

<?php
function perms($array) {
    $res = array( array() );
    foreach ($array as $val) {
        $n = count($res);
        for($i=0; $i < $n; $i++) {
            $res[] = array_merge( array($val), $res[$i] );
        }
    }
    return $res;
}
$array = array("one", "two", "three");
print_r( perms($array) );

Result can be found on Ideone. The output is in a multi-dimensional form, but I'm sure you can figure out how to flatten that.

Upvotes: 1

Drahakar
Drahakar

Reputation: 6088

It seems like you are looking for a powerset, here is a link to the algorithm : http://en.wikipedia.org/wiki/Power_set

Upvotes: 1

Related Questions