Opposite of array_intersect?

前端 未结 5 1094
盖世英雄少女心
盖世英雄少女心 2021-02-06 20:36

Is there a built-in function to get all members of array 1 which do not exist in array 2?
I know how to do it programatically, only wondering if there is a built-in function

5条回答
  •  不思量自难忘°
    2021-02-06 21:23

    array_diff is definitely the obvious choice but it is not technically the opposite of array interesect. Take this example:

    $arr1 = array('rabbit','cat','dog');
    
    $arr2 = array('cat','dog','bird');
    
    print_r( array_diff($arr1, $arr2) );
    

    What you want is a result with 'rabbit' and 'bird' in it but what you get is only rabbit because it is looking for what is in the first array but not the second (and not vice versa). to truly get the result you want you must do something like this:

    $arr1 = array('rabbit','cat','dog');
    
    $arr2 = array('cat','dog','bird');
    
    $diff1 = array_diff($arr1, $arr2);
    $diff2 = array_diff($arr2, $arr1);
    print_r( array_merge($diff1, $diff2) );
    

    Note: This method will only work on arrays with numeric keys.

提交回复
热议问题