Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
  • How can you get all the combinations of given string in php?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.56k
    Comment on it

    We can generate all possible combinations of given string. Here I made a function get_string_combinations($str), this function will accept string as a parameter and will give you all possible combinations of that string. In this function, I have converted given string into an array of words by using explode function. Then counted the number of words in that array by using the count() function.


    The pow() function is used to calculate the result of exponent and power by multiplying the exponent as a number of times as power. Here I have used bin() function to convert decimal number to binary number. str_pad() function is used to pad the string to new length, by default, it will pad to the right side of the string, I gave the parameter  " STR_PAD_LEFT "  pad to the left side of the string.


    Here is the code:

    print_r(get_string_combinations("sun mon tue"));
    function get_string_combinations($strng)
        $words = explode(' ',$strng);
        $elements = pow(2, count($words))-1;
        $result = array();
        for ($i = 1; $i<=$elements; $i++)
            $bin = decbin($i);
            $padded_bin = str_pad($bin, count($words), "0", STR_PAD_LEFT);
            $res = array();
            for ($k=0; $k<count($words); $k++)
                if ($padded_bin[$k]==1){
                    $res[] = $words[$k];
            $result[] = implode("_", $res);
        return $result;


    output will be:


        [0] => tue
        [1] => mon
        [2] => mon_tue
        [3] => sun
        [4] => sun_tue
        [5] => sun_mon
        [6] => sun_mon_tue

 0 Comment(s)

Sign In

Sign up using

Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: