Home > Article > Backend Development > How to delete the intersection of two arrays in php
In PHP programming, it is very common to encounter the problem of deleting the intersection of two arrays, especially when the intersection of multiple arrays needs to be processed. This article will introduce you to a simple and practical method to delete the intersection between two arrays.
1. Problem Description
Suppose there are two arrays $A and $B, respectively as follows:
$A = array(1,2,3,4,5 ,6);
$B = array(4,5,7,8,9,10);
The requirement is to retain only all elements of $A and $B, but not two The intersection part in the arrays, that is, the result array should be:
$Result = array(1,2,3,6,7,8,9,10);
So what should I do? What about implementation? The following will introduce you one by one.
2. Method 1
First of all, we can use the array_diff function in PHP to implement the difference operation of array elements. The code is as follows:
$Result = array_merge(array_diff ($A, $B), array_diff($B, $A));
In the above code, array_diff($A, $B) means filtering out items in the $A array but not in $B Elements in the array; array_diff($B, $A) means to filter out elements that are in the $B array but not in the $A array. Then use the array_merge function to combine the two result arrays. This method seems simple, but in fact it is not robust, as shown in the following points:
So, in order to better avoid these problems, we need to use a more robust method to delete the intersection of array elements.
3. Method 2
Next, we can loop through each element in the array, and perform deduplication and filtering operations in the process. The code is as follows:
$Result = array();
foreach($A as $value){
if(!in_array($value, $B)){ $Result[] = $value; }
}
foreach($B as $value){
if(!in_array($value, $Result)){ $Result[] = $value; }
}
In the above code, we first define an empty array $Result, representing the final result array. Then use two foreach loops to iterate through each element in $A and $B. During the process, use the in_array function to determine whether the current element appears in another array, such as whether it appears in $B. If it does not appear before, it is added to $Result. The final $Result array is the union of all elements in the two arrays.
Using this method has the following advantages:
4. Summary
In PHP, this article introduces two ways to deal with array intersection problems: using the array_diff function and loop traversal filtering. Although both methods can get correct results, the method of using loop traversal is more robust and can handle more edge cases, which is worth learning.
The above is the detailed content of How to delete the intersection of two arrays in php. For more information, please follow other related articles on the PHP Chinese website!