Checking to see if one array's elements are in another array in PHP

前端 未结 7 1813
闹比i
闹比i 2020-11-27 13:26

I have two arrays in PHP as follows:

People:

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

Wanted Criminals:

相关标签:
7条回答
  • 2020-11-27 13:59

    Performance test for in_array vs array_intersect:

    $a1 = array(2,4,8,11,12,13,14,15,16,17,18,19,20);
    
    $a2 = array(3,20);
    
    $intersect_times = array();
    $in_array_times = array();
    for($j = 0; $j < 10; $j++)
    {
        /***** TEST ONE array_intersect *******/
        $t = microtime(true);
        for($i = 0; $i < 100000; $i++)
        {
            $x = array_intersect($a1,$a2);
            $x = empty($x);
        }
        $intersect_times[] = microtime(true) - $t;
    
    
        /***** TEST TWO in_array *******/
        $t2 = microtime(true);
        for($i = 0; $i < 100000; $i++)
        {
            $x = false;
            foreach($a2 as $v){
                if(in_array($v,$a1))
                {
                    $x = true;
                    break;
                }
            }
        }
        $in_array_times[] = microtime(true) - $t2;
    }
    
    echo '<hr><br>'.implode('<br>',$intersect_times).'<br>array_intersect avg: '.(array_sum($intersect_times) / count($intersect_times));
    echo '<hr><br>'.implode('<br>',$in_array_times).'<br>in_array avg: '.(array_sum($in_array_times) / count($in_array_times));
    exit;
    

    Here are the results:

    0.26520013809204
    0.15600109100342
    0.15599989891052
    0.15599989891052
    0.1560001373291
    0.1560001373291
    0.15599989891052
    0.15599989891052
    0.15599989891052
    0.1560001373291
    array_intersect avg: 0.16692011356354
    
    0.015599966049194
    0.031199932098389
    0.031200170516968
    0.031199932098389
    0.031200885772705
    0.031199932098389
    0.031200170516968
    0.031201124191284
    0.031199932098389
    0.031199932098389
    in_array avg: 0.029640197753906
    

    in_array is at least 5 times faster. Note that we "break" as soon as a result is found.

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