phparraysfilterassociative-arrayarray-difference

Why is array_diff() excluding elements with same value, but different keys when comparing?


I have an array_diff() function between 2 associative arrays and the result is not as it should be. I don't understand why it does not return the status value as a difference. First array is the input array to be filtered, the second is the filtering array, and the third is the result. In the result, it should contain 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"
}

Solution

  • 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);