PHP - Check if two arrays are equal

后端 未结 15 2071
说谎
说谎 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 12:04

    According to this page.

    NOTE: The accepted answer works for associative arrays, but it will not work as expected with indexed arrays (explained below). If you want to compare either of them, then use this solution. Also, this function may not works with multidimensional arrays (due to the nature of array_diff function).

    Testing two indexed arrays, which elements are in different order, using $a == $b or $a === $b fails, for example:

    
    

    That is because the above means:

    array(0 => "x", 1 => "y") vs. array(0 => "y", 1 => "x").

    To solve that issue, use:

    
    

    Comparing array sizes was added (suggested by super_ton) as it may improve speed.

提交回复
热议问题