Home » PHP/MySQL, Programming Techniques » PHP – possible combinations between multiple array elements

I have no reasons for posting this article here. But I’m sure someone can get some insight from this. This is a good example of making use of recursive function calls also known as recursion. It takes the form of a function that calls itself. Recursive functions or recursion are something that needs a little more attention as you have to be sure that the function call finally ends somewhere.

A useful way to think of recursive functions is to imagine them as a process being performed where one of the instructions is to “repeat the process”.

A simple example to show how recursion works would be a function that finds the factorial of an integer.

<?php
    function factorial($number) {
        if ($number == 0) return 1;
        return $number * factorial($number - 1);
    }
    print factorial(6);
?>

What we need is a function that will accept an integer, and, if that integer is not 0, will call the function again, this time passing in the same number it accepted minus 1, then multiply that result by itself. If it is sounding hard, then you are in for a surprise: the function to calculate factorials is made up of only two lines of code. As you can see, recursive functions make programming certain tasks particularly easy.

Let’s come back to my problem. I have got a number of arrays which has many elements in it. The problem is to find all the possible combination between all the elements of these arrays. You can see below how I solved it in PHP.

I have these arrays. It could be any number of arrays.

$a1 = array(“01″, “02″);
$a2 = array(“white”, “green”);
$a3 = array(“one”, “two”, “three”);

I want this as the output.

01 one green
01 two green
01 three green
01 one white
01 two white
01 three white
02 one green
02 two green
02 three verde
02 one white
02 two white
02 three white

And the solution to this problem in PHP is this.

<?php
$a = array("01", "02");
$b = array("white", "green");
$c = array("one", "two", "three");
$aG = array($a, $b, $c);
$codes = array();
$pos = 0;
generateCodes($aG);
function generateCodes($arr) {
    global $codes, $pos;
    if(count($arr)) {
        for($i=0; $i<count($arr[0]); $i++) {
            $tmp = $arr;
            $codes[$pos] = $arr[0][$i];
            $tarr = array_shift($tmp);
            $pos++;
            generateCodes($tmp);
        }
    } else {
        echo join(", ", $codes)."<br/>";
    }
    $pos--;
}
?>

Let me know if you have any questions on this.

13 Comments

  1. Abhinaya Panigrahi says:

    Hi

    Realy u people are doing well.
    by using this code i only want to say waaaaaooooooo………

    Thanks
    Abhi

  2. Dan says:

    Thanks for sharing. Here’s the associative version:

    header('Content-Type: text/plain');

    $a = array("01", "02");
    $b = array("white", "green");
    $c = array("one", "two", "three");
    $aG = array($a, $b, $c);
    $aG = array('asdf'=>$a, 'color'=>$b, 'yxcv'=>$c);
    $codes = array();
    $pos = 0;
    generateCodes($aG);

    function generateCodes($arr) {
    global $codes, $pos;
    if (count($arr)) {
    for ($i = 0, $c=count($arr[key($arr)]); $i < $c; $i++) {
    $tmp = $arr;
    $codes[key($arr)] = $arr[key($arr)][$i];
    $tarr = array_shift($tmp);
    $pos++;
    generateCodes($tmp);
    }
    } else {
    print_r($codes);
    }
    $pos--;
    }

  3. Aneeska says:

    Cool Dan!

    Thanks,
    Anees

  4. malczu says:

    Version without global:

    $a = array(“01″, “02″);
    $b = array(“white”, “green”);
    $c = array(“one”, “two”, “three”);
    $aG = array($a, $b, $c);
    $aG = array(‘asdf’=>$a, ‘color’=>$b, ‘yxcv’=>$c);

    $out = generateCodes($param);

    function generateCodes($arr, &$out = array(), $codes = array(), $pos = 0) {
    if(count($arr)) {
    $first_count = count(current($arr));
    foreach( current($arr) as $item) {
    $tmp = $arr;
    $codes[$pos] = $item;
    $tarr = array_shift($tmp);
    $pos++;
    generateCodes($tmp, $out, $codes, $pos);
    $pos–;
    }
    } else {
    $out[] = $codes;
    }

    return $out;
    }

  5. R. Hanouwer says:

    My solution to the problem:

    function combine($r, $c = ”) {
    if($s = (array)array_shift($r)) foreach($s as $p) foreach(combine($r, $c) as $t) $o[] = $p.$t; else return (array)$c;
    return $o;
    }

  6. Chris says:

    Thanks for this tutorial. I have been trying to do something similar, but just can not figure it out. I was wondering if you could provide some insight. I have a SQL statement that creates a multidimensional array that consist of times that are in a sequence of at least four consecutive order:

    Array
    (
    [0] => Array
    (
    [0] => 13:00:00
    [1] => 14:00:00
    [2] => 15:00:00
    [3] => 16:00:00
    )

    [1] => Array
    (
    [0] => 18:00:00
    [1] => 19:00:00
    [2] => 20:00:00
    [3] => 21:00:00
    [4] => 22:00:00
    )

    )

    What I want to do is create check boxes for each possible 4 hours with a start and end time:

    Checkbox 1 = 9:00 am – 12:00 pm
    Checkbox 2 = 10:00 am – 1:00 pm
    Checkbox 3 = 11:00 am – 2:00 pm

    And so on…

    Any thoughts?

  7. Matija says:

    Hi there. I need some help. If i have M arrays with N elements in each array (for example: array1 = {D1,D2,…Dn}, array2 ={O1,O2,..On},…arrayM={… }), i want to generate only ONE possible combination with elements from each array, assuming that any elements can repeat, but only N times. This is like representation of a WAVELENGTH SELECTIVE optical network, in which one DEMUX (D1) has N wavelengths, each of them can be sent to exactly ONE O1 switch, and then to one MUX M. One combination of those elements represents one lightpath, and different lightpath are passing through same elements, but only N lightpaths in one elements. If anybody can help me, I would be thankful. Best regards!!

  8. DEEPAK says:

    Thanks…
    very good code

  9. Francis says:

    Exactly what I was looking for. Thank you so much!

  10. RAdhikari says:

    Can Anybody please give its C# Code.
    Thanks in Advance.

  11. Jamie says:

    I know this is a few years old now, but does anyone know how to modify this code to prevent same values, for example, array(a,b,c,d,e,f), array(a,b,c), array(b,c,d). i need all combinations with out repeats. for example, no a, a, a,
    just:
    a,b,c;
    a,b,d
    a,c,d etc
    Thank you in advance!

Leave a Reply

Page optimized by WP Minify WordPress Plugin