PHP: Return all String Permutations for a 1 Dimensional Array CodeUnit 07 FEB 2011

Getting all the possible string permutations of an array can be pretty useful if you are trying to unlock something and this nifty little function does exactly that:

function array_permutations($items, $perms = array()) {
    static $permuted_array;
    if (empty($items)) {
        $permuted_array[] = $perms;
    } else {
        for ($i = count($items) - 1; $i >= 0; --$i) {
            $newitems = $items;
            $newperms = $perms;
            list($foo) = array_splice($newitems, $i, 1);
            array_unshift($newperms, $foo);
            array_permutations($newitems, $newperms);
        }
        return $permuted_array;
    }
}

//To use:
$result=array_permutations(array("South","Africa","Rugby","Competition"));
print_r($result); 

Nifty.

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.

  • Rsmartz

    I tried this function and works great for a an array of 8 elements, but when I add more the script breaks.. any solution

  • Arwie

    works great, thank you