0

I want to get all possible phrases (which actually exist) in a sentence as

$str = 'word1 word2 word3 word4';

$output = array ('word1 word2 word3', 'word1 word2', 
                 'word2 word3 word4', 'word3 word4', 'word2 word3');

To do so, I create an array of words as,

$words = explode(' ', $str);

There are several questions here explaining how to build all combinations of the elements of an array, but how can I make all the combinations while preserving the original order?

How can I make the array of $output out of $words?

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
Googlebot
  • 15,159
  • 44
  • 133
  • 229

1 Answers1

1
  • We can use array_slice() function to take a chunk out of the input array. It will also ensure that the order is maintained, as well as the combinations are of the successive values (as per the original array).
  • Now, we need to use two nested loops, to determine $offset, and $length for the chunk.
  • $offset value will basically loop from the beginning to end; $length will initially be count of remaining values from the offset, and it will be decrementing upto 2 (we don't want single values as combinations).

Try the following (Rextester DEMO):

$str = 'word1 word2 word3 word4';
$words = explode(' ', $str);

$combinations = array();

// offset from start to end of the words
for($offset = 0; $offset < count($words); $offset++) {

    // length from available remaining words to 2
    for ($length = count($words) - $offset; $length > 1; $length--) {

        // get the array chunk
        $combinations[] = array_slice($words, $offset, $length);
    }
}

// test output
print_r($combinations);

Output:

Array
(
    [0] => Array
        (
            [0] => word1
            [1] => word2
            [2] => word3
            [3] => word4
        )

    [1] => Array
        (
            [0] => word1
            [1] => word2
            [2] => word3
        )

    [2] => Array
        (
            [0] => word1
            [1] => word2
        )

    [3] => Array
        (
            [0] => word2
            [1] => word3
            [2] => word4
        )

    [4] => Array
        (
            [0] => word2
            [1] => word3
        )

    [5] => Array
        (
            [0] => word3
            [1] => word4
        )

)
Madhur Bhaiya
  • 28,155
  • 10
  • 49
  • 57