phparrayscombinations

Generate a 2d array of all two-element combinations from a flat array


I am not sure how to exactly explain what I am trying to do but I try to explain using an example.

$products = array("35","37","43");

Say if I have above array how can I create a result array that will look like this.

$related_products = array (
    array (35,37),
    array (35,43),
    array (37,35),
    array (37.43),
    array (43,35),
    array (43, 37)
)

Solution

  • You could use two loops to catch all combinations:

    $products = array("35","37","43");
    $result = array();
    for($i = 0; $i < count($products); $i++) {
        for($j = 0; $j < count($products); $j++) {
            if($i !== $j) {
                $result[] = array(
                    $products[$i],
                    $products[$j]
                );
            }   
        }
    }
    
    print_r($result);
    

    Result:

    Array
    (
        [0] => Array
            (
                [0] => 35
                [1] => 37
            )
    
        [1] => Array
            (
                [0] => 35
                [1] => 43
            )
    
        [2] => Array
            (
                [0] => 37
                [1] => 35
            )
    
        [3] => Array
            (
                [0] => 37
                [1] => 43
            )
    
        [4] => Array
            (
                [0] => 43
                [1] => 35
            )
    
        [5] => Array
            (
                [0] => 43
                [1] => 37
            )
    
    )