Home > Article > Backend Development > Deep Thoughts on the Differences of PHP Array Traversal (Implementation of array_diff)_PHP Tutorial
function array_diff($array_1, $array_2) {
$diff = array();
foreach ($array_1 as $k => $v1) {
$flag = false;
foreach ($array_2 as $v2) {
if ($flag = ($v1 == $v2)) {
break;
}
}
$flag) {
$diff[$k] = $v1; The efficiency is appalling. So I reconsidered and optimized the algorithm. The second function looked like this:
function array_diff($array_1, $array_2) {
foreach ($array_1 as $key => $item) {
if (in_array($item, $array_2, true)) {
unset($array_1[$key]);
}
}
return $array_1;
} Well, this time it’s almost as fast as the original array_diff function. But is there a more optimized way? From an article on ChinaUnix (sorry, I cheated), I found that PHP can actually write like this:
function array_diff($array_1, $array_2) {
$array_2 = array_flip($array_2) ;
foreach ($array_1 as $key => $item) {
if (isset($array_2[$item])) {
unset($array_1[$key]);
}
}
return $array_1;
} The efficiency of this function is amazing, even faster than the original array_diff function. Investigating the reason, I found an explanation:
Because the keys are HASH organized, the search is very fast;
The Value is only stored in the Key organization and has no index itself. Each search is traversed. Summary
Although this is a little trick of the PHP language, when traversing and comparing array values, if you need to compare the value, reversing it with the key is indeed much more efficient than the usual value-to-value comparison.
For example, function two above needs to call the in_array function and needs to loop to determine whether it is within the function; while function three only determines whether the key exists in the array. Coupled with the different organizational indexing methods of array keys and values, it is very understandable that the efficiency is higher than imagined.
Attach code
Copy code
The code is as follows: