Compare arrays

1

Good afternoon.

I would like to know how I can be comparing two arrays and saving each pair of found values and printing the numbers that were unparalleled.

Ex: a) 1,2,3,4,5     b) 1,3,5,6,7,5,3

It would hold the pairs (1,1) (3,3) (5,5) and print the values 2,4,6,7,5,3 Notice that 5 and 3 also have to be printed because not another one that keeps the same pair.

I need to know exactly those values that are not even, even though they are repeated. If anyone can give a light, grateful.

Hugs

    
asked by anonymous 29.03.2016 / 20:10

2 answers

2

I believe that this code results in the problem, first a search is done on the array $b passing the current value of $a , if found it is created a new element in $iguais which basically does the same thing as array_diff() and this item is removed from $b to not enter the count again. Otherwise an item is added to $diferentes . Finally, the sum of the items that exist in $a that do not exist in $b with this line is done: ( $diferentes += $b; )

Example - ideone

<?php
$a = [1,2,3,4,5];
$b = [1,3,5,6,7,5,3];

$iguais = [];
$diferentes = [];
foreach($a as $item){
    $i = array_search($item, $b);
    if($i !== false){
        $iguais[] = '('. $item .', '. $b[$i] .')';
        unset($b[$i]);
    }else{
        $diferentes[] = $item;
    }
}

$diferentes += $b;

echo "<pre>";
print_r($iguais);

echo "<pre>";
print_r($diferentes);

Output:

Array
(
    [0] => (1, 1)
    [1] => (3, 3)
    [2] => (5, 5)
)

Array
(
    [0] => 2
    [1] => 4
    [3] => 6
    [4] => 7
    [5] => 5
    [6] => 3
)
    
29.03.2016 / 21:02
2

PHP has a function called array_diff .

Basically what it does is what you want, the difference is you will need to give it a few more iterations because it shows only the differences between two arrays, then in the example given by the php site:

<?php
$array1 = array("a" => "verde", "vermelho", "azul", "vermelho");
$array2 = array("b" => "verde", "amarelo", "vermelho");
$result = array_diff($array1, $array2);
print_r($result);
?>

The result would be

Array
(
  [1] => azul
)

The opposite of this function would be what you could look for to make the first step, the array_intersect joins two arrays as a inner join and returns the values that exist in both:

<?php
$array1 = array("a" => "verde", "vermelho", "azul");
$array2 = array("b" => "verde", "amarelo", "vermelho");
$result = array_intersect($array1, $array2);
print_r($result);
?>

Return:

Array
(
    [a] => verde
    [0] => vermelho
)
    
29.03.2016 / 20:21