Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,959 questions

51,901 answers

573 users

How to generate all possible permutations of a string in PHP

1 Answer

0 votes
function swap(&$s, $i, $j) {
    $tmp = $s[$i];
    $s[$i] = $s[$j];
    $s[$j] = $tmp;
}   

function generate_permutations($s, $i, $len) {
    if ($i == $len)
       echo "$s\n";
    else {
        for ($j = $i; $j < $len; $j++) {
            swap($s, $i, $j);
            generate_permutations($s, $i + 1, $len);
        }
    }
}

 
$s = "ab";
generate_permutations($s, 0, strlen($s)); 
 
echo "\n";
 
$s = "abc";
generate_permutations($s, 0, strlen($s)); 
 
echo "\n";
 
$s = "abcd";
generate_permutations($s, 0, strlen($s)); 




        
/*
run:
             
ab
ba

abc
acb
bac
bca
cab
cba

abcd
abdc
acbd
acdb
adbc
adcb
bacd
badc
bcad
bcda
bdac
bdca
cabd
cadb
cbad
cbda
cdab
cdba
dabc
dacb
dbac
dbca
dcab
dcba
      
*/

 



answered May 31, 2017 by avibootz
edited Dec 18, 2023 by avibootz
...