PHP - all combinations of upper and lower case characters of a string

I am trying to get all combinations of upper and lower case characters of a string. For example my string abc

. I need to get a result like this: all combinations for three characters of the string (2^0) x (2^1) x (2^2) = 8

::

abc
Abc
ABc
ABC
aBC
abC
AbC
aBc

      

My code is this, but I have a problem, my code has duplicate cases and does not return abc

and abc

:

<?php
function opposite_case($str) 
{ 
    if(ctype_upper($str)) 
    { 
        return strtolower($str); 
    } 
    else 
    { 
        return strtoupper($str); 
    } 
} 

$str = "abc";

for($i = 0 ; $i < strlen($str) ; $i++)
{
    for($j = 0 ; $j < strlen($str) ; $j++) 
    {
        $str[$j] = opposite_case($str[$j]);
        echo $str."<br>"; 
    }
}
?>

      

+3


source to share


1 answer


A bit about the code dump with some comments added for a good estimate. This was converted from Java implementation - fooobar.com/questions/759381 / ...

http://sandbox.onlinephpfunctions.com/code/000e55236510216aa499dc54e092c94853f82b00



<?php

function calculatePermutations($text) {

    $permutations = array();
    $chars = str_split($text);

    // Count the number of possible permutations and loop over each group 
    for ($i = 1; $i < strlen($text) ** 2; $i++) {

        // Loop over each letter [a,b,c] for each group and switch its case
        for ($j = 0; $j < strlen($text); $j++) {

            // isBitSet checks to see if this letter in this group has been checked before
            // read more about it here: http://php.net/manual/en/language.operators.bitwise.php
            $permutations[$i][] = (isBitSet($i, $j)) 
                ? strtoupper($chars[$j]) 
                : $chars[$j];
        }
    }

    return $permutations;
}

function isBitSet($n, $offset) {
  return ($n >> $offset & 1) != 0;
}

print_r(calculatePermutations('abc'));

      

+1


source







All Articles