开发者

Compare to values of two arrays in PHP

开发者 https://www.devze.com 2022-12-26 12:39 出处:网络
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 la

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 )

开发者_如何学C

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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消