comparing arrays in php, without caring for the order

前端 未结 5 743
借酒劲吻你
借酒劲吻你 2020-12-10 03:42

I have two arrays, $a and $b here, and need to check if they contain exactly the same elements (independently of the order). I am thinking of using

if (sizeo         


        
5条回答
  •  执笔经年
    2020-12-10 04:24

    Well, we can do something like this:

    if (count(array_diff(array_merge($a, $b), array_intersect($a, $b))) === 0) {
        //they are the same!
    }
    

    The reason it works, is that array_merge will make a big array that has all the elements of both $a and $b (all the elements that are in either $a, $b, or both). array_intersect will create an array that has all the elements that are in both $a and $b only. So if they are different,, there must be at least one element that does not appear in both arrays...

    Also note that sizeof is not an actual function/construct, it's an alias. I'd suggest using count() for clarity...

提交回复
热议问题