-5

array is like this : $arr = array("a","b","c","d");

I want to combine it. The result must have "abcd" and not repeat.

Example : $r = array("ab","cd") || array("a","bcd") || array("abcd") || array("ab","c","d")

Now I use the following function:

function combination(){  
$str = array("a","b","c","d");  
$result = array();  
$c = count($str);  
$nbin = 1 << $c;  
for($i = 1; $i < $nbin; $i++){  
        $element = "";  
        for($j=0;$j < $c; $j++){  
                if((1 << $j & $i) !=0 ){  
                        $element .= $str[$j];  
                }  
        }  
        array_push($result,$element);  
}  
        return $result;  
}  

This is the $result:

Array
(
    [0] => a
    [1] => b
    [2] => ab
    [3] => c
    [4] => ac
    [5] => bc
    [6] => abc
    [7] => d
    [8] => ad
    [9] => bd
    [10] => abd
    [11] => cd
    [12] => acd
    [13] => bcd
    [14] => abcd
)

How should I do this?

Guillaume Jacquenot
  • 11,217
  • 6
  • 43
  • 49
xuzeng
  • 1
  • 2

1 Answers1

0

I'm a little uncertain what exactly you are expecting to be returned by your code. Assuming all you want returned is element 14 of your array (ONLY abcd), you can use the PHP function implode. This concatenates all the elements in the array together. i.e.,

$array = array('a', 'b', 'c', 'd');
var_dump(implode($array));
var_dump(implode('-', $array));

will return string 'abcd' and then string 'a-b-c-d'

I hope this answers what you were asking.

Michael Thompson
  • 541
  • 4
  • 21