'How to store each element as source and destination from array in php?

I am having one array with some elements and i want output where i can store each element in table as source and destination too. e.g

    $array = ['1','2','3,'4'];
     
    source | destination |
------------------------------
    1      | 2           |
    1      | 3           |
    1      | 4           |
    2      | 1           |
    2      | 3           |
    2      | 4           |
    3      | 1           |
    3      | 2           |
    3      | 4           |
    4      | 1           |
    4      | 2           |
    4      | 3           |

I want to store data like above structure. I tried with for each loop but not getting perfect logic for this.Please help me solve this.



Solution 1:[1]

A loop in a loop with a quick check so you dont print when the indices are the same is all you need

$array = [1,2,3,4];

for ($i=0; $i<count($array); $i++){
    for ( $j=0; $j<count($array); $j++){
        if ( $i == $j ) {
            continue;
        }
        echo sprintf("%d - %d\n", $array[$i], $array[$j]);    
    }
}

RESULT

1 - 2
1 - 3
1 - 4
2 - 1
2 - 3
2 - 4
3 - 1
3 - 2
3 - 4
4 - 1
4 - 2
4 - 3

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 RiggsFolly