1

Hello i have an array_dif function between 2 arrays and the result it's not as it should.I don't understand why it does not return the status as difference. First array is data second is row and the third is the result. In the result it should also be status because the value is different.

$result = array_diff($data,$row );
array(9) {
  ["scooter_id"]=>
  string(6) "RO0001"
  ["battery_lvl"]=>
  string(2) "80"
  ["lat"]=>
  string(9) "44.312150"
  ["lng"]=>
  string(9) "23.872900"
  ["alt"]=>
  string(1) "0"
  ["speed"]=>
  string(1) "0"
  ["status"]=>
  string(1) "2"
  ["ip"]=>
  string(14) "213.233.101.62"
  ["port"]=>
  int(24600)
}

array(11) {
  ["battery_lvl"]=>
  string(2) "80"
  ["nr_satelites"]=>
  string(1) "1"
  ["lat"]=>
  string(9) "44.312154"
  ["longi"]=>
  string(9) "23.873007"
  ["alt"]=>
  string(1) "0"
  ["speed"]=>
  string(1) "0"
  ["status"]=>
  string(1) "1"
  ["location"]=>
  string(7) "romania"
  ["ip"]=>
  string(14) "213.233.101.62"
  ["port"]=>
  string(5) "24600"
  ["status_intermediar"]=>
  string(1) "2"
}

array(3) {
  ["scooter_id"]=>
  string(6) "RO0001"
  ["lat"]=>
  string(9) "44.312150"
  ["lng"]=>
  string(9) "23.872900"
}
chris227
  • 579
  • 9
  • 28

3 Answers3

1
$array_difference1 = array_merge(array_diff($array1, $array2),
    array_diff($array2, $array1));

$array_differnce = array_merge(array_diff($array_difference1, $array3),
    array_diff($array3, $array_difference1));
Rahul
  • 18,271
  • 7
  • 41
  • 60
1

array_dif is one way function ("Compares array1 against one or more other arrays and returns the values in array1 that are not present in any of the other arrays."- https://www.php.net/manual/en/function.array-diff.php).

If you want all diffs, you have to call it twice: array_dif($first, $second) and array_dif($second, $one) and optionally merge results.

PeliCan
  • 196
  • 1
  • 1
  • 8
  • Even though if he runs it twice with the supplied values he will get `status` as a difference it is only situational bacause if array1 had an element with a value of 1 it would still not return `status` as a difference – Dimitris Filippou Jun 10 '19 at 09:12
1

array_diff checks only the values.

Because your 2nd array contains ["status_intermediar"]=> string(1) "2" it finds the value so it doesn't see it as a difference

If you want to check both keys and values you should use array_diff_assoc

Also if you want to find all the different values from BOTH arrays you should run it twice

$difference1=array_diff_assoc($array1,$array2);

$difference2=array_diff_assoc($array2,$array1);