4

How to create possible combinations of strings from string in php

Exp:

input = 'abc';
output = array(
  [0]=> "a"
  [1]=> "ab"
  [2]=> "abc"
  [3]=> "ac"
  [4]=> "acb"
  [5]=> "b"
  [6]=> "ba"
  [7]=> "bac"
  [8]=> "bc"
  [9]=> "bca"
  [10]=> "c"
  [11]=> "ca"
  [12]=> "cab"
  [13]=> "cb"
  [14]=> "cba"
)

Please Help, Thanks

1

3 Answers 3

3

Fasil kk's code could run into a "Maximum function nesting level" fatal error,

If you have this problem, try this instead:

$letters = str_split("abc");

$combos = $letters;
$lastres = $letters;
for ($i = 1; $i < count($letters); $i++) {
    $newres = array();
    foreach ($lastres as $r) {
        foreach ($letters as $let) {
            $newres[] = $r . $let;
        }
    }

    foreach ($newres as $w) {
        $combos[] = $w;
    }

    $lastres = $newres;
}

print_r($combos);

then you just need to worry about memory :)

Sign up to request clarification or add additional context in comments.

Comments

1

Convert string characters to an array, create all possible combination by creating two loops.

example:This code works perfectly(tested).

  <?PHP
    function create_possible_arrays(&$set, &$results)
    {
        for ($i = 0; $i < count($set); $i++)
        {
            $results[] = $set[$i];
            $tempset = $set;
            array_splice($tempset, $i, 1);
            $tempresults = array();
            create_possible_arrays($tempset, $tempresults);
            foreach ($tempresults as $res)
            {
                $results[] = $set[$i] . $res;
            }
        }
    }

    $results = array();
    $str = 'abc'; //your string
    $str = str_split($str); //converted to array
    create_possible_arrays($str, $results);
    print_r($results); //displaying all results
    ?>

Comments

0

I'm ok with Axxe (thanks), but you have to remove duplicate values from the combo array.

I propose this function :

function create_possible_arrays($string) {
    $letters = str_split($string);

    $combos = array_unique($letters);
    $lastres = $letters;
    for ($i = 1; $i < count($letters); $i++) {
        $newres = array();
        foreach ($lastres as $r) {
            foreach ($letters as $let) {
                $new = $r . $let;
                if (!in_array($new, $newres)) {
                    $newres[] = $new;

                    // Action
                    $combos[] = $new;
                }

            }
        }

        $lastres = $newres;

    }

    return $combos;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.