1

I am creating a possible combinations of the string from the input given by the user in my form.

Eg : string : "samsung s duos";

I have to create a combinations such as

samsung
s
duos

samsung s
samsung duos
s duos

The order of the combination should start from left to right only.

So what i did is

$input = $_post['inputstring'];

$productNameSplit = explode(" ",$input);


$cntsplit = count($productNameSplit);

for($i=0; $i<$cntsplit; $i++)
{
   echo "<br>";                    
   echo "Part1 : ".$part1= $productNameSplit[$i];
   echo "<br><br>";
   echo "Part2 :".$part2 = $productNameSplit[$i]." ".$productNameSplit[$i+1]."<br>";
   echo "<br>";
   echo "Part3 :".$part3 = $productNameSplit[$i+1]." ".$productNameSplit[$i]."<br>";
}

print_r(productNameSplit);

OUTPUT

Array ( [0] => samsung [1] => s [2] => duos ) 


Part1 : samsung

Part2 :samsung s

Part3 :s samsung // i dont want this since s samsung = samsung s

Part1 : s

Part2 :s duos

Part3 :duos s // i dont want this since s duos = duos s

Part1 : duos

Notice: Undefined offset: 3 in Part2 :duos 

Notice: Undefined offset: 3 in Part3 : duos

i didn't get 'samsung duos'

Raaga
  • 569
  • 1
  • 5
  • 17

3 Answers3

0

try this one

$input = "samsung s duos";

$arr_names = explode(" ",$input);
$cnt_names = count($arr_names);
for($i=0; $i<$cnt_names; $i++)
{
    echo $arr_names[$i]."<br/>";
    for($j=$i+1; $j<$cnt_names; $j++)
    {
        echo $arr_names[$i]." ".$arr_names[$j]."<br/>";
    }

}

OUTPUT :

samsung
samsung s
samsung duos
s
s duos
duos

DEMO

Satish Sharma
  • 9,547
  • 6
  • 29
  • 51
0

What you are looking for is a power set, please have a look at the following post: Finding the subsets of an array in PHP

[Edit:] Please be aware that the other solutions here do not work for combinations of arbitrary size (I'am not allowed to comment on them).

Community
  • 1
  • 1
RCKY
  • 43
  • 6
0

Output :

samsung s  
samsung duos  
s duos  

Demo here : https://eval.in/170783

PHP :

function combinaison($array, $level = 0) {
    for ($i = $level+1; $i < count($array); $i++)
        echo "{$array[$level]} {$array[$i]}  \n";

    if (isset($array[$level+1]))
        combinaison($array, $level+1);
}

combinaison(explode(" ", "samsung s duos"));

Optimized :

function combinaison($array, $level = 0) {
    for ($i = $level+1; $i < count($array); $i++)
        echo "{$array[$level]} {$array[$i]}  \n";
    (isset($array[$level+1])) && combinaison($array, $level+1);
}
user2226755
  • 12,494
  • 5
  • 50
  • 73