tags:

views:

91

answers:

5

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

A: 

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.

animuson
+3  A: 
    $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) ;
Brant
+1  A: 

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

Michael
+4  A: 

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

Sebastian P.
A: 

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

konforce