Check if two arrays have the same values

后端 未结 9 1320
既然无缘
既然无缘 2020-12-15 02:45
[2,5,3]    

[5,2,3]

They are equal because they have the same values, but not in the same order. Can I find out that without using a foreach loop

相关标签:
9条回答
  • 2020-12-15 03:35

    If you don't want to sort arrays but just want to check equality regardless of value order use http://php.net/manual/en/function.array-intersect.php like so:

    $array1 = array(2,5,3);
    $array2 = array(5,2,3);
    if($array1 === array_intersect($array1, $array2) && $array2 === array_intersect($array2, $array1)) {
        echo 'Equal';
    } else {
        echo 'Not equal';
    }
    
    0 讨论(0)
  • 2020-12-15 03:43

    Say, if you have two arrays defined like this:

    $array1 = array(2,5,3);
    $array2 = array(5,2,3);
    

    Then you can use this piece of code to judge whether they equal:

    if(array_diff($array1,$array2) === array_diff($array2,$array1) &&count($array1)==count($array2))
    {
        echo 'Equal';
    }
    else
    {
        echo 'Not equal';
    }
    
    0 讨论(0)
  • 2020-12-15 03:44
    sort($a);
    sort($b);
    if ($a==$b) {//equal}
    
    0 讨论(0)
提交回复
热议问题