Compare to values of two arrays in PHP

前端 未结 6 1371
南方客
南方客 2021-01-20 14:56

Hi i want to compare all the values of 2 arrays and end up with a true or false . I am using the code below and would of thought that the result would be false . but that is

相关标签:
6条回答
  • 2021-01-20 15:00

    array_diff gives which elements are in $before but not $after. Since both arrays consist of '0' and '1', it returns an empty array.

    What you're looking for is array_diff_assoc, which looks at keys and values together.

    Do note, the output you get will not be Array( [0] => 0 ), but rather Array( [0] => 1 ), as it gives the elements from the first array that doesn't exist in the other one.

    If you wish the other output, you'll need to do array_diff_assoc($after, $before).

    0 讨论(0)
  • 2021-01-20 15:00

    Yes, array_diff does spot a difference. It finds the differences between the following arrays with the first one. It doesn't compare 0 to 0 and 1 to 1, however. It simply checks if each value in Array1 is in Array2 ... ArrayN. This function returns an array of all the occurrences in Array1 that were not found in the other arrays, not a true/false boolean. See example 1 in the documentation.

    0 讨论(0)
  • 2021-01-20 15:13
        $before = array('1', '1', '0', '0', '1', '0' ) ;
        $after =  array('0', '1', '0', '0', '1', '0' ) ;
    
        $new_array= array_diff_assoc($before,$after);
    
        print_r ($new_array) ;
    
    0 讨论(0)
  • 2021-01-20 15:15

    It might sound silly, but comparing two array of different lengths will NOT yield expected difference. Check the length of the arrays first and if they match then use array_diff. Otherwise your diff will always be empty.

    0 讨论(0)
  • 2021-01-20 15:16

    Hi i want to compare all the values of 2 arrays and end up with a true or false

    $bool = ($array1 == $array2);
    

    http://us2.php.net/manual/en/language.operators.array.php

    0 讨论(0)
  • 2021-01-20 15:21

    See http://php.net/manual/en/function.array-diff.php

    "Multiple occurrences in $array1 are all treated the same way."

    So, since all you have a zeros and ones, everything is "the same."

    0 讨论(0)
提交回复
热议问题