1

If I have a string $input and explode it into an array like this, then $arr should contain each of the four words

$input = "hello everybody at here";
$arr = explode(" ",$input);

But I would like to get all combination possibilities, like this:

hello everybody at here
hello everybody at
hello everybody
hello
everybody at here
etc

How can I do this? :D

Thanks

jsherk
  • 6,128
  • 8
  • 51
  • 83
Phan Hai
  • 35
  • 1
  • You can loop through the array two times: One time backwards and one time forwards. Go ahead and think of how that would help you solve your problem :) – Tobias F. Dec 17 '17 at 15:10
  • Possible duplicate of [Need string formation with space in php](https://stackoverflow.com/questions/47691979/need-string-formation-with-space-in-php) – Andreas Dec 17 '17 at 15:19
  • andreas: no i don't think so – Phan Hai Dec 17 '17 at 15:24
  • Sorry, I linked to the wrong thread – Andreas Dec 17 '17 at 15:45
  • Think about a 4-bits binary number, `0000` to `1111`, `0` is hidden, `1` is shown, ie counting from 1 to 15 in your case... – Déjà vu Dec 17 '17 at 17:04
  • Why is this thread upvoted? There is no attempts at all – Andreas Dec 17 '17 at 17:06
  • hi, anyone have code for this case :D – Phan Hai Dec 18 '17 at 02:36
  • Do you want all possible combinations (like https://pastebin.com/kCNMsrLa ), or do you want to keep words' position order? – CronosS Dec 18 '17 at 11:49
  • This post will point you in the right direction - https://stackoverflow.com/questions/10834393/php-how-to-get-all-possible-combinations-of-1d-array – tbedner Dec 18 '17 at 15:01
  • Possible duplicate of [PHP: How to get all possible combinations of 1D array?](https://stackoverflow.com/questions/10834393/php-how-to-get-all-possible-combinations-of-1d-array) – Progman Dec 18 '17 at 16:42

1 Answers1

0

You can check this: (using a recursive function)

$input = "hello everybody at here";
$array = explode(" ",$input);

function permutation($arr, $ts, &$newArray)
{
    if ($ts != "")
        $newArray[] = $ts;

    for ($i = 0; $i < count($arr); $i++) {
        $temp = $arr;
        $elem = array_splice($temp, $i, 1);
        if (count($temp) > 0) {
            permutation($temp, $ts . " " . $elem[0], $newArray);
        } else {
            $newArray[] = $ts . " " . $elem[0];
        }
    }
}

$newArray = [];
permutation($array, "", $newArray);
print_r($newArray);

Demo: https://3v4l.org/OP5XD

Hitesh Vaghani
  • 174
  • 1
  • 11