简体   繁体   中英

How to create possible combinations of strings from string in php?

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

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
    ?>

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 :)

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM