How to compare 2 arrays to find which value is missing in one of them, using PHP

Asked

Viewed 67 times

0

I have 2 arrays and need to make a comparison between them, to find what values are missing in the 2nd array ($arrayxml), for example:

$arraybd=array('1','2','3','4');
$arrayxml=array('1','2');

In this case the values are missing '3' and '4' in $arrayxml, then take these values '3' and '4' to be able to perform the task I need (I will remove it from the database).

The ideal would be to generate a string, or even an array with the values that are missing, in the above case, would be:

$valoresdiferentes=('3','4')

What’s the best way to do that?

2 answers

4


You can use the function array_diff_assoc, she does exactly what you want.

$arraybd=array('1','2','3','4');
$arrayxml=array('1','2');
$diferencas = array_diff_assoc($arraybd, $arrayxml);
print_r($diferencas);
  • show, what is the difference between the array_diff_assoc and diff?

  • @Leandromarzullo a diff_assoc array_also includes the keys in the comparison, if only the values use the same diff array_example, if you have an array as follows $array("a" => "value1", "b" => "value2"); and another $array2 array("value1", "b" => "value2"); It will consider the "valor1" of array2 to be different because it does not have the key "a"

2

You can use the function array_diff().

$arraybd=array('1','2','3','4');
$arrayxml=array('1','2');

$result = array_diff($arrayxml, $arraybd);

print_r($diferencas);

//irá printar 3 e 4

According to the php documentation, first pass the array to be compared, and then the array to compare. The result will always be all entries of array 1 that I am not in other arrays.

Browser other questions tagged

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