I’ve two arrays like this:
$arr = Array (1, 2, 3 ,4 ,5, 6 ,7 ,8 ) ;
and this:
$arr2 = Array (7, 6, 5,8 ,3 ,2 ,1, 4 )
The pairs of these arrays are the numbers with the same key ($arr[0]-$arr2[0] ecc.)
1-7
2-6
3-5
4-8
5-3
6-2
7-1
8-4
as you can see there are some duplicate pairs like 1-7 and 7-1 , 2-6 and 6-2 , 3-5 and 5-3, 4-8 and 8-4.
I need a function who recives these two arrays and return one array with each single pairs.
For example this is what the function should returns:
Array ( [0] => 1 [1] => 7 [2] => 2 [3] => 6 [4] => 3 [5] => 5 [6] => 4 [7] => 8 )
As you can see the pairs ares: 1-7 , 2-6, 3-5 and 4-8.
I’ve made this function who doesnt work properly:
function free_pairs($arr,$arr2){
$ok = 0;
$ris = array();
$indice_ris=0;
for ($i=1; $i <=count($arr) ; $i++) {
$x1 = $arr[$i];
$x2 = $arr2[$i];
for ($j=1; $j <= count($arr2) ; $j++) {
$y1 = $arr[$j];
$y2 = $arr2[$j];
if($x1 != $y2 && $x2 != $y1){
$ok = 1;
} else {
$ok = 0;
}
}
if ($ok == 1) {
$ris[$indice_ris] = $x1;
$ris[$indice_ris+1] = $x2;
$indice_ris = $indice_ris+2;
$ok = 0;
}
return $ris;
}
I think the problem is in this if:
if($x1 != $y2 && $x2 !=$y1)
What do you think about?
After some corrections on your original script, this seems to work:
output: