PHP - Check if two arrays are equal

后端 未结 15 2153
说谎
说谎 2020-11-22 11:26

I\'d like to check if two arrays are equal. I mean: same size, same index, same values. How can I do that?

Using !== as suggested by a user, I expect th

15条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 11:54

    if (array_diff($a,$b) == array_diff($b,$a)) {
      // Equals
    }
    
    if (array_diff($a,$b) != array_diff($b,$a)) {
      // Not Equals
    }
    

    From my pov it's better to use array_diff than array_intersect because with checks of this nature the differences returned commonly are less than the similarities, this way the bool conversion is less memory hungry.

    Edit Note that this solution is for plain arrays and complements the == and === one posted above that is only valid for dictionaries.

提交回复
热议问题