An effective way to implement array union in PHP: use the array_merge() function to merge multiple arrays, but not merge duplicate values. Combine array_unique() and array_merge() to merge arrays and keep duplicate values. Create a custom function to merge arrays based on specific requirements, such as merging sorted arrays.
Effective implementation of array union in PHP
Introduction
In PHP , array union means merging two or more arrays, returning only one copy of each element. This is useful in situations where you need to merge two arrays or concatenate multiple arrays. This article will introduce some common methods for effectively implementing the union of arrays.
Method 1: array_merge()
array_merge()
function is one of the simplest ways to implement array union. It combines multiple arrays into one and returns a new array. However, if there are elements with the same key but different values, array_merge()
will not merge them, but will use the value from the first array.
$arr1 = [1, 2, 3]; $arr2 = [3, 4, 5]; $result = array_merge($arr1, $arr2); // 结果: [1, 2, 3, 3, 4, 5]
Method 2: array_unique() array_merge()
If you need to merge arrays and keep all values (including duplicate values), you can use it in conjunction with array_unique ()
and array_merge()
. array_unique()
will remove duplicate values from an array, while array_merge()
will merge two arrays.
$arr1 = [1, 2, 3]; $arr2 = [3, 4, 5]; $result = array_merge(array_unique($arr1), array_unique($arr2)); // 结果: [1, 2, 3, 4, 5]
Method 3: Custom function
For situations with specific requirements, you can also create a custom function to implement array union. For example, the following function can merge sorted arrays:
function array_merge_sorted($arr1, $arr2) { $result = []; $i = $j = 0; while ($i < count($arr1) && $j < count($arr2)) { if ($arr1[$i] == $arr2[$j]) { $result[] = $arr1[$i]; $i++; $j++; } elseif ($arr1[$i] < $arr2[$j]) { $result[] = $arr1[$i]; $i++; } else { $result[] = $arr2[$j]; $j++; } } while ($i < count($arr1)) { $result[] = $arr1[$i]; $i++; } while ($j < count($arr2)) { $result[] = $arr2[$j]; $j++; } return $result; } // 实战案例 $arr1 = [1, 2, 3, 5, 7, 9]; $arr2 = [2, 4, 6, 8, 10]; $result = array_merge_sorted($arr1, $arr2); // 结果: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Conclusion
Depending on the specific requirements, this can be achieved efficiently using one of the various methods discussed above PHP array union. For simple cases, the array_merge()
function is sufficient, while for cases with specific requirements, custom functions can be used to implement custom logic.
The above is the detailed content of Effective implementation of array union in PHP. For more information, please follow other related articles on the PHP Chinese website!