Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP array_diff weirdness

Tags:

php

This is such a simple problem but the PHP doc does not explain why it is happening.

I have this code:

var_dump($newattributes); var_dump($oldattributes);
var_dump(array_diff($newattributes, $oldattributes));

For briefity I am going to omit large parts of the structure I am actually using (since each is 117 elements long) and cut to the case.

I have one array called $newattributes which looks like:

array(117){
    // Lots of other attributes here
    ["deleted"] => int(1)
}

And another called $oldattributes which looks like:

array(117){
    // Lots of other attributes here
    ["deleted"] => string(1) "0"
}

Which looks different right? According to array_diff: no. The output I get from array_diff is:

array(0) { } 

I have read the documentation page however it says:

Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.

And I am not sure how "1" can object equal "0".

So am I seeing some caveat with array_diff I didn't take into consideration?

like image 635
Sammaye Avatar asked Aug 17 '12 10:08

Sammaye


1 Answers

The problem might reside in the fact that you are using associative arrays : you should try and use the following for associative arrays : array_diff_assoc():

<?php 
    $newattributes = array(
       "deleted" => 1 
    );

    $oldattributes = array(
       "deleted" => "0" 
    );

    $result = array_diff_assoc($newattributes, $oldattributes);

    var_dump($result);
?>

result :

   array(1) {
       ["deleted"]=>
       int(1)
   }
like image 62
DonSeba Avatar answered Sep 30 '22 11:09

DonSeba