The efficiency of PHP's array_diff of function when dealing with large arrays

  • 2020-05-10 17:48:36
  • OfStack

The method that cisa submits to the PHP official BUG page
 
<?php 
/** 
*  To solve  php 5.2.6  The above version  array_diff()  The function is processing  
*  The problem of taking too long for large arrays  
* 
*  Finish: http://www.CodeBit.cn 
*  Source: http://bugs.php.net/47643 
*/ 
function array_diff_fast($data1, $data2) { 
$data1 = array_flip($data1); 
$data2 = array_flip($data2); 
foreach($data2 as $hash => $key) { 
if (isset($data1[$hash])) unset($data1[$hash]); 
} 
return array_flip($data1); 
} 
?> 

Rewrite the method according to ChinaUnix forum moderator hightman
 
<?php 
/** 
*  To solve  php 5.2.6  The above version  array_diff()  The efficiency of a function when dealing with large arrays  
*  According to the  ChinaUnix  BBS moderator  hightman  The way you write it  
* 
*  Finish: http://www.CodeBit.cn 
*  Reference: http://bbs.chinaunix.net/viewthread.php?tid=938096&rpid=6817036&ordertype=0&page=1#pid6817036 
*/ 
function array_diff_fast($firstArray, $secondArray) { 
//  Convert the first 2 The key-value relationship of an array  
$secondArray = array_flip($secondArray); 
//  Circle the first 1 An array  
foreach($firstArray as $key => $value) { 
//  If the first 2 A number exists in an array 1 The value of an array  
if (isset($secondArray[$value])) { 
//  Remove the first 1 The corresponding elements in an array  
unset($firstArray[$key]); 
} 
} 
return $firstArray; 
} 
?> 

This method only swaps the key and value of the second array, so it is more efficient.
Note: while PHP's built-in array_diff() function can handle multiple arrays, the method presented in this article only handles the comparison of two arrays.

Related articles: