php - Recursion function over multidimensional array


I have an array and in this array are 3 arrays with attributes, sometimes the array can have more or less..

[0] => Array
        [0] => XS
        [1] => S
        [2] => M
        [3] => L
        [4] => XL

[1] => Array
        [0] => Black
        [1] => Red
        [2] => Green

[2] => Array
        [0] => Fitted
        [1] => Not Fitted


And would like to then echo out recursively..

XS Black Fitted
XS Black Not Fitted
XS Red Fitted
XS Red Not Fitted
XS Green Fitted
XS Green Not Fitted
S Black Fitted
S Black Not Fitted
S Red Fitted
S Red Not Fitted
S Green Fitted
S Green Not Fitted
M Black Fitted
... And so on

I do have code but nothing workable to show anything meaningful. Recursion confuses me and can't seem to produce a recursive function in a way that will produce this.. Any help would be appreciated :)




This is what you need to achieve this combination from php associative arrays. I found this useful method on a github gist when I had to do this type of combination from php associative array, Hope this will help you also.

function get_combinations($arrays) {
    $result = array(array());
    foreach ($arrays as $property => $property_values) {
        $tmp = array();
        foreach ($result as $result_item) {
            foreach ($property_values as $property_value) {
                $tmp[] = array_merge($result_item, array($property => $property_value));
        $result = $tmp;
    return $result;

$array = [['XS','S','M','L','XL'],['Black','Red','Green'],['Fitted','Not Fitted']];

$combinations = get_combinations($array);
print '<pre>';
print '</pe>';
foreach($combinations as $key=>$value){
   echo implode(' ', $value)."\n";


People are also looking for solutions to the problem: php - table ci_session doesn't exist error


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.