Shuffling php string

Solution:1

This is sample function for shuffling any characters. You can use only shuffle_string function for your purpose.

// direct function for shuffling characters of any string
function shuffle_string ($string) {
    $string_len = strlen($string);
    permute($string, 0, $string_len);
}
// to generate and echo all N! permutations of $string.
function permute($string, $i, $n) {
    if ($i == $n) {
        echo "$string\n";
    } else {
        for ($j = $i; $j < $n; $j++) {
            swap($string, $i, $j);
            permute($string, $i+1, $n);
            swap($string, $i, $j); // backtracking.
        }
    }
}
// to swap the character at position $i and $j of $string.
function swap(&$string, $i, $j) {
    $temp = $string[$i];
    $string[$i] = $string[$j];
    $string[$j] = $temp;
}
shuffle_string('Hey');

Solution:2

Hope this will help:

<?php
function permutations($set)
{
$solutions=array();
$n=count($set);
$p=array_keys($set);
$i=1;

while ($i<$n)
    {
    if ($p[$i]>0)
        {
        $p[$i]--;
        $j=0;
        if ($i%2==1)
            $j=$p[$i];
        //swap
        $tmp=$set[$j];
        $set[$j]=$set[$i];
        $set[$i]=$tmp;
        $i=1;
        $solutions[]=$set;
        }
    elseif ($p[$i]==0)
        {
        $p[$i]=$i;
        $i++;
        }
    }
return $solutions;
}

$string = 'abc';
$string = str_split($string);
$all_per = permutations($string);
foreach($all_per as $key => $value){
    $str[]= implode(',',$value);
}
print_r($str);