I have an array having three element $base =(#m, #f,#p)
I have a second array having any number of element like $var = (s1, s2)
Now i need to create all possible combinations depending only on the base array. The formula I found is x pow y.
In this example my base array has three element and $var has 2, so  pow(3, 2) is 9. I need these nine combinations. i.e
#m#m #m#f #m#p
#f#m #f#f #f#p
#p#m #p#f #p#p
The number of elements in the 2nd array is in effect the length of the generated combinations. As in this example the length of the 2nd array is 2 so all generated strings have length 2.
You can use a recursive function like this:
// input definition
$baseArray = array("#m", "#f", "#p");
$varArray = array("s1", "s2", "s3");
// call the recursive function using input
$result = recursiveCombinations($baseArray, sizeof($varArray));
// loop over the resulting combinations
foreach($result as $r){
    echo "<br />combination " . implode(",", $r);
}
// this function recursively generates combinations of #$level elements
// using the elements of the $base array
function recursiveCombinations($base, $level){
    $combinations = array();
    $recursiveResults = array();
    // if level is > 1, get the combinations of a level less recursively
    // for level 1 the combinations are just the values of the $base array
    if($level > 1){
        $recursiveResults = recursiveCombinations($base, --$level);
    }else{
        return $base;   
    }
    // generate the combinations
    foreach($base as $baseValue){
        foreach($recursiveResults as $recursiveResult){
            $combination = array($baseValue);
            $combination = array_merge($combination, (array)$recursiveResult);  
            array_push($combinations, $combination);
        }
    }
    return $combinations;
}
Working codepad demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With