Compare two arrays with PHP

Asked

Viewed 669 times

0

I am 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
  • explains a little better what exactly Oce wants to return to the user, I didn’t quite understand this list.

  • So it’s better ? @Neuberoliveira

  • I couldn’t understand what you want to do with these values, the arrays are cluttered and you want to compare the values from the array’s input to the input? And then you want to do what with the result? You want to merge the 2 arrays in an orderly fashion?

  • See array_intersect and array_diff in the PHP manual, it might help..

1 answer

1

I think that’s it, just need to give an adapted because here I am taking into account that one array can be larger than another, the way I did it can reverse 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 ? ' ^' : '');
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.