Search code examples
phparrayscombinations

Use a flat array of single words to create new arrays with increasing numbers of words per array element


I have an array with words below as an example.

$words = array('hello','world','wad','up','yo','etc');

What I want is next array with following by manipulating above

$phrase2 = array('hello world', 'world wad', 'wad up', 'up  yo', 'yo etc');
$phrase3 = array('hello world wad', 'world wad up', 'wad up yo', 'up  yo etc');
$phrase4 = array('hello world wad up', 'world wad up yo', 'wad up yo etc');
$phrase5 = array('hello world wad up yo', 'world wad up yo etc');

Solution

  • Slice array and then implode the results:

    $words = array('hello','world','wad','up','yo','etc');
    $phrase2 = array();
    $phrase3 = array();
    $phrase4 = array();
    $lim = sizeof($words);
    for($i=0;$i<$lim;$i++)
    {
        if($i < $lim - 1)
            $phrase2[] = implode(" ",array_slice($words,$i,2)); 
        if($i < $lim - 2)
            $phrase3[] = implode(" ",array_slice($words,$i,3)); 
        if($i < $lim - 3)
            $phrase4[] = implode(" ",array_slice($words,$i,4)); 
    }