0

I've created an array with $my_array = range(1,3) and I'd like to have an array created containing all the permutations of this one (1,2,3 1,3,2 2,1,3 ..).

The second number in the range function can change (it could be 4, 5, 7, 50 instead of 3).

Bruno
  • 8,497
  • 13
  • 38
  • 55
  • possible duplicate of [Algorithm to return all combinations of k elements from n](http://stackoverflow.com/questions/127704/algorithm-to-return-all-combinations-of-k-elements-from-n) – Yoshi Sep 19 '11 at 09:17
  • Plenty of answers about cartesian products already, try searching. – Nev Stokes Sep 19 '11 at 09:17

1 Answers1

0

Code from Christer's blog o' fun :

function permute($str) {
    /* If we only have a single character, return it */
    if (strlen($str) < 2) {
        return array($str);
    }

    /* Initialize the return value */
    $permutations = array();

    /* Copy the string except for the first character */
    $tail = substr($str, 1);

    /* Loop through the permutations of the substring created above */
    foreach (permute($tail) as $permutation) {
        /* Get the length of the current permutation */
        $length = strlen($permutation);

        /* Loop through the permutation and insert the first character of the original
        string between the two parts and store it in the result array */
        for ($i = 0; $i <= $length; $i++) {
            $permutations[] = substr($permutation, 0, $i) . $str[0] . substr($permutation, $i);
        }
    }

    /* Return the result */
    return $permutations;
}

$array_of_natural_numbers = range(1, 5);
$string_of_natural_numbers = implode("",$array_of_natural_numbers);
$permutations = permute($string_of_natural_numbers);
outis
  • 75,655
  • 22
  • 151
  • 221
Bruno
  • 8,497
  • 13
  • 38
  • 55