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

0

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

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

In this case, the values '3' and '4' are missing in $arrayxml , so I would get those values '3' and '4' to be able to execute the task I need (I'll 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 case above, would be:

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

What is the best way to do this?

    
asked by anonymous 13.11.2018 / 11:00

2 answers

4

You can use the array_diff_assoc function, it does exactly what you either.

$arraybd=array('1','2','3','4');
$arrayxml=array('1','2');
$diferencas = array_diff_assoc($arraybd, $arrayxml);
print_r($diferencas);
    
13.11.2018 / 11:19
2

You can use the array_diff() function.

$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 , you should first pass the array to be compared, and then the array to compare. The result will always be all entries in array 1 that I'm not in the other arrays.

    
13.11.2018 / 11:21