I want to compare two arrays in PHP

前端 未结 6 1745
萌比男神i
萌比男神i 2021-01-20 23:45

Assume that I have two arrays as follow:

$array1 = array(1, 3, 5);
$array2 = array(\'x\'=> 1, \'y\'=> 2, \'z\'=> 5);

How to check that

6条回答
  •  伪装坚强ぢ
    2021-01-21 00:08

    In the simplest case you can just use array_diff. It ignores the keys in your second array, but also the order of the values. It would return an empty set if the arrays are equal:

     if (count(array_diff($array1, $array2)) == 0) {
        // equal
    

    You could also compare the arrays directly, after stripping keys from the second:

     if ($array1 == array_values($array2)) {
    

    That would additionally compare the order of contained values.

提交回复
热议问题