Home >Backend Development >PHP Tutorial >How Can I Generate All Permutations of a String in PHP?
Permutations of a String in PHP
In PHP, generating all permutations of characters within a string involves an algorithm that systematically explores all possible combinations.
Backtracking Approach
One effective approach is backtracking. Here's the PHP implementation:
function permute($str,$i,$n) { if ($i == $n) print "$str\n"; else { for ($j = $i; $j < $n; $j++) { swap($str,$i,$j); permute($str, $i+1, $n); swap($str,$i,$j); // backtrack. } } } function swap(&$str,$i,$j) { $temp = $str[$i]; $str[$i] = $str[$j]; $str[$j] = $temp; } $str = "hey"; permute($str,0,strlen($str)); // call the function.
Explanation
Output
Executing the code with $str = "hey" produces the expected output:
hey hye ehy eyh yeh yhe
The above is the detailed content of How Can I Generate All Permutations of a String in PHP?. For more information, please follow other related articles on the PHP Chinese website!