How to print all possible permutations (all possible orderings) of the words in PHP

3 Answers

0 votes
function print_words_permutations($items, $perms = array()) {
    if (empty($items)) {
        echo implode(' ', $perms) . "\n";
    } else {
        for ($i = 0; $i < count($items); $i++) {
            $newItems = $items;
            $newPerms = $perms;
            list($foo) = array_splice($newItems, $i, 1);
            array_unshift($newPerms, $foo);
            print_words_permutations($newItems, $newPerms);
        }
    }
}
 
$words = ["word-1", "word-2", "word-3"];

print_words_permutations($words);
 
 
 
/*
run:
 
word-3 word-2 word-1
word-2 word-3 word-1
word-3 word-1 word-2
word-1 word-3 word-2
word-2 word-1 word-3
word-1 word-2 word-3
 
*/
 

 



answered Jan 20, 2025 by avibootz
edited Apr 14 by avibootz
0 votes
function print_words_permutations($items, $current = []) {
    if (empty($items)) {
        echo implode(" ", $current) . "\n";
        return;
    }

    foreach ($items as $key => $item) {
        $remaining = $items;
        unset($remaining[$key]);

        print_words_permutations($remaining, array_merge($current, [$item]));
    }
}

$words = ["word-1", "word-2", "word-3"];

print_words_permutations($words);



/*
run:

word-1 word-2 word-3
word-1 word-3 word-2
word-2 word-1 word-3
word-2 word-3 word-1
word-3 word-1 word-2
word-3 word-2 word-1

*/

 



answered Apr 14 by avibootz
0 votes
function get_words_permutations($items) {
    if (count($items) <= 1) {
        return [$items];
    }

    $result = [];

    foreach ($items as $key => $item) {
        $remaining = $items;
        unset($remaining[$key]);

        foreach (get_words_permutations($remaining) as $perm) {
            $result[] = array_merge([$item], $perm);
        }
    }

    return $result;
}

$words = ["word-1", "word-2", "word-3"];
$permutations = get_words_permutations($words);

print_r($permutations);

 
 
/*
run:
 
Array
(
    [0] => Array
        (
            [0] => word-1
            [1] => word-2
            [2] => word-3
        )

    [1] => Array
        (
            [0] => word-1
            [1] => word-3
            [2] => word-2
        )

    [2] => Array
        (
            [0] => word-2
            [1] => word-1
            [2] => word-3
        )

    [3] => Array
        (
            [0] => word-2
            [1] => word-3
            [2] => word-1
        )

    [4] => Array
        (
            [0] => word-3
            [1] => word-1
            [2] => word-2
        )

    [5] => Array
        (
            [0] => word-3
            [1] => word-2
            [2] => word-1
        )

)

*/
 

 



answered Apr 14 by avibootz

Related questions

...