comparing arrays in php, without caring for the order

前端 未结 5 752
借酒劲吻你
借酒劲吻你 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:06

    If you think of the arrays as sets:

    Then your approach is almost correct (you need to drop the equality test for the element count).

    If it matters that the arrays contain multiple copies of the same element:

    Then your approach is not correct. You need to sort the arrays with sort and then compare them with ===. This should be faster, as it can abort the comparison the moment it sees one difference without going over the whole arrays.

    Update:

    Clarified exactly when the OP's approach would be correct or not, also incorporated the suggestion that sort would be probably better than asort here.

提交回复
热议问题