PHP Program to print all permutations of a given string

A permutation, also called an “arrangement number” or “order, ” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation.
Source: Mathword(http://mathworld.wolfram.com/Permutation.html)

Below are the permutations of string ABC.
ABC ACB BAC BCA CBA CAB

Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.

PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to print all 
// permutations of a given string.
  
  
/**
* permutation function
* @param str string to 
*  calculate permutation for
* @param l starting index
* @param r end index
*/
function permute($str, $l, $r)
{
    if ($l == $r)
        echo $str. "\n";
    else
    {
        for ($i = $l; $i <= $r; $i++)
        {
            $str = swap($str, $l, $i);
            permute($str, $l + 1, $r);
            $str = swap($str, $l, $i);
        }
    }
}
  
/**
* Swap Characters at position
* @param a string value
* @param i position 1
* @param j position 2
* @return swapped string
*/
function swap($a, $i, $j)
{
    $temp;
    $charArray = str_split($a);
    $temp = $charArray[$i] ;
    $charArray[$i] = $charArray[$j];
    $charArray[$j] = $temp;
    return implode($charArray);
}
  
// Driver Code
$str = "ABC";
$n = strlen($str);
permute($str, 0, $n - 1);
  
// This code is contributed by mits.
?>

chevron_right


Output:



ABC
ACB
BAC
BCA
CBA
CAB

Please refer complete article on Write a program to print all permutations of a given string for more details!



My Personal Notes arrow_drop_up


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.