Home  >  Article  >  Backend Development  >  Detailed explanation of the timeout BUG problem of PHP's array_diff() function when processing large arrays

Detailed explanation of the timeout BUG problem of PHP's array_diff() function when processing large arrays

巴扎黑
巴扎黑Original
2017-05-23 18:02:152083browse

The array_diff() function of PHP 5.2.6 and above takes an extremely long time when processing large arrays. This bug has been officially confirmed; before this problem is fixed or when we cannot control the PHP version, you can Use the method provided in this article

cisa Submit it to the PHP official BUG page

The code is as follows:

<?php 
/** 
* 解决 php 5.2.6 以上版本 array_diff() 函数在处理 
* 大数组时的需要花费超长时间的问题 
* 
* 整理:http://www.CodeBit.cn 
* 来源: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); 
} 
?>


According to the idea of ​​​​ChinaUnix Forum moderator hightman The rewritten method

The code is as follows:

<?php 
/** 
* 解决 php 5.2.6 以上版本 array_diff() 函数在处理大数组时的效率问题 
* 根据 ChinaUnix 论坛版主 hightman 思路写的方法 
* 
* 整理:http://www.CodeBit.cn 
* 参考:http://bbs.chinaunix.net/viewthread.php?tid=938096&rpid=6817036&ordertype=0&page=1#pid6817036 
*/ 
function array_diff_fast($firstArray, $secondArray) { 
// 转换第二个数组的键值关系 
$secondArray = array_flip($secondArray); 
// 循环第一个数组 
foreach($firstArray as $key => $value) { 
// 如果第二个数组中存在第一个数组的值 
if (isset($secondArray[$value])) { 
// 移除第一个数组中对应的元素 
unset($firstArray[$key]); 
} 
} 
return $firstArray; 
} 
?>

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

The above is the detailed content of Detailed explanation of the timeout BUG problem of PHP's array_diff() function when processing large arrays. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn