Skip to content
Advertisement

Combine neighbouring elemets to new array of min 2

I have a quite specific problem. I want to combine every element of an array with neighboring elements to a new array of minimum length 2. Im not sure if Im explaining that correctly so here’s an example:

Given the array:

$array = ['a', 'b', 'c', 'd'];

I want to create a new array that looks like this:

[
  ['ab', 'c', 'd'],
  ['ab', 'cd'],
  ['abc', 'd'],
  ['a', 'bc', 'd'],
  ['a', 'bcd'],
  ['a', 'b', 'cd']
]

[‘abcd’] is not returned since it is only of length 1.

Advertisement

Answer

I thought I would post an answer since I got it working with help from others.

function permutations($array, $i)
{
    if($i >= count($array) - 1)
    {
        return array($array);
    }

    $newArray = $array;
    $newArray[$i] .= $newArray[$i + 1];

    unset($newArray[$i+1]);

    $newArray = array_values($newArray);

    $a = permutations($newArray, $i );

    $b = permutations( $array, $i + 1);

    return array_merge($a, $b);
}

//$array = ['a', 'b', 'c', 'd'];

//print_r(permutations($array, 0));
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement