简体   繁体   中英

Compare to values of two arrays in PHP

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 not the case , when the last line runs I would expect a display something like

Array ( [0] => 0 )

but I get no display so assume that php is happy that there is no difference

my code is

        $before = array('1', '1', '0', '0', '1', '0' ) ;
        $after =  array('0', '1', '0', '0', '1', '0' ) ;

        $new_array= array_diff($before,$after);

        print_r ($new_array) ;

surely the array_diff should spot a difference here ? any help would be great thanks

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 isarray_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) .

    $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) ;

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."

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM