What is the most efficient way to remove all the elements of one array from another array?

前端 未结 3 2007
有刺的猬
有刺的猬 2021-01-12 03:47

I have two arrays, array A contains a long list with some elements I want to remove. Array B is the full list of those elements that I wish to remove from array A.

W

相关标签:
3条回答
  • 2021-01-12 04:24

    In the manual it gives for array_dif() this exaple:

    <?php
    $array1 = array("a" => "green", "red", "blue", "red");
    $array2 = array("b" => "green", "yellow", "red");
    $result = array_diff($array1, $array2);
    
    print_r($result);
    ?>
    

    Outputs:

    Array
    (
        [1] => blue
    )
    

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

    0 讨论(0)
  • 2021-01-12 04:38

    array_diff is the obvious answer, but since you've asked for the most efficient way, here's a test

    $big = range(1, 90000);
    $remove = range(500, 600);
    
    $ts = microtime(true);
    $result = array_diff($big, $remove);
    printf("%.2f\n", microtime(true) - $ts);
    
    $ts = microtime(true);
    $map = array_flip($remove);
    $result = array();
    foreach($big as $e)
        if(!isset($map[$e]))
            $result[] = $e;
    printf("%.2f\n", microtime(true) - $ts);
    

    prints on my machine

    0.67
    0.03
    

    So the simple loop with a hash-based lookup is approximately 20 times faster than array_diff.

    0 讨论(0)
  • 2021-01-12 04:38

    Use array_diff()

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