In PHP, how can I find elements in one array that are not in another?

后端 未结 3 952
南笙
南笙 2020-12-20 14:27

Is there a php function, similar to array_merge, that does the exact opposite? In other words, I have two arrays. I would like to remove any value that exists in the second

相关标签:
3条回答
  • 2020-12-20 15:06
     $array1 = array(1, 2, 3, 4, 5);
     $array2 = array(2, 4, 5);
     $result = array_diff($array1, $array2);
    
    0 讨论(0)
  • 2020-12-20 15:17

    You can use array_diff() to compute the difference between two arrays:

    $array1 = array(1, 2, 3, 4, 5);
    $array2 = array(2, 4, 5);
    
    $array3 = array_diff($array1, $array2);
    print_r($array3);
    

    Output:

    Array
    (
        [0] => 1
        [2] => 3
    )
    

    Demo!

    0 讨论(0)
  • 2020-12-20 15:17

    array_diff

    Returns an array containing all the entries from array1 that are not present in any of the other arrays.

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