Compare two arrays with PHP

0

I'm developing a project where I need to compare two arrays and organize the values.

Example:

# Objeto 1
$array1 = [1, 2, 3];
# bjeto 2
$array2 = [2, 1, 3];

I need to show the user a list of this type:

Comparison:

Obj 1 | Obj 2
  1   |   2^ (maior)
  2^  |   1
  3   |   3
    
asked by anonymous 23.08.2016 / 13:11

1 answer

1

I think that's it, you just have to adapt it because here I'm taking into account that one array can be larger than another, the way I did it, you can invert the objects.

$array1 = [1, 2, 3];
$array2 = [2, 1, 3, 4, 5];
$resultado = [];

//arrayG = Greater array com o maior tamanho
$arrayG = $array1;
//arrayL = Lower array com o meno tamanho
$arrayL = $array2;

//tamanho dos arrays
$array1Size = count($array1);
$array2Size = count($array2);

//isso define qual o maior array, acho mais facil para fazer o for, alem de iterar em so 1 array
if($array2Size>$array1Size){
    $arrayG = $array2;
    $arrayL = $array1;
}

echo "Objeto 1 | Objeto 2<br>";
foreach($arrayG as $i=>$v1){
    //Aqui so verifico se o valor existe no array menor
    if(isset($arrayL[$i]) ){
        $v2 = $arrayL[$i];
    }else{
        $v2 = 0;
    }

    //note que aqui eu inverti os valores que passo para a funcao
    echo getGreaterValue($v1, $v2).' | '.getGreaterValue($v2, $v1).'<br>';
}


function getGreaterValue($v1, $v2){
    return $v1.' '.($v1>$v2 ? ' ^' : '');
}
    
23.08.2016 / 14:11