How to check if two indexed arrays have same values even if the order is not same in PHP?

后端 未结 2 1778
名媛妹妹
名媛妹妹 2021-01-22 12:22

I want to compare two indexed arrays as such that values will be same for two arrays but order may differ, for example i tried doing this but it simply doesn\'t work.

Ex

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-22 13:07

    Instead of comparing the return values of sort, why don't you just compare the arrays after they have been sorted?

    $a = array(1,2,3,4,5);
    sort($a);
    $b = array(1,2,3,5,4);
    sort($b);
    echo ($a == $b) ? 'Match Found' : 'No Match Found';
    

    If the arrays have different keys but the same values, they will still count as equal. You must also compare the array keys if this is an issue.

提交回复
热议问题