Skip to content
Advertisement

Generate word combinations

For example this is my text :

$str = 'buy new microsoft windows';

I explode text and list with array :

Array
(
    [0] => buy
    [1] => new
    [2] => microsoft
    [3] => windows
)

I want to generate words in array to something like this:

buy new
buy new windows
buy microsoft 
buy microsoft windows
buy windows
new microsoft
new microsoft windows
new windows
microsoft windows

I tried with foreach and rand but I couldn’t generate like showed. Is there any chance to generate just like my request?

Advertisement

Answer

You can have a look at this PEAR PACKAGE Example usage:

<?php
require_once 'Math/Combinatorics.php';
$words = array('buy', 'new', 'microsoft');
$combinatorics = new Math_Combinatorics;
foreach($combinatorics->permutations($words, 2) as $p) {
  echo join(' ', $p), "n"; 
}

The output will be:

buy new
new buy
buy microsoft
microsoft buy
new microsoft
microsoft new
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement