Removal steps: 1. Use array_intersect() to obtain duplicate values (intersection elements) of two arrays. The syntax "array_intersect(original array 1, (original array 2)" will return an intersection array; 2. Use array_diff() to compare the two original arrays and the intersection array respectively to obtain the difference set, that is, delete duplicate values and obtain non-duplicate elements. The syntax is "array_diff (original array 1, intersection array)" and "array_diff (original array 2) , intersection array)".
The operating environment of this tutorial: Windows 7 system, PHP version 8.1, DELL G3 computer
How to remove two Duplicate values that exist in both arrays, that is, intersection elements?
Example: There are two arrays like this:
$arr1=array(1,2,3,4,5,6,7,8,9); $arr2=array(2,4,6,8,10,12,14,16);
The duplicate values that exist in both arrays are:
2、4、6、8
How to remove these duplicate values?
In PHP, you can use the array_intersect() and array_diff() functions to delete duplicate values from two arrays.
Implementation steps:
Step 1: Use array_intersect() function to obtain repeated values (intersection elements) of two arrays
array_intersect() function can be compared The values of the two arrays and return the intersection array containing duplicate values.
$intersect=array_intersect($arr1,$arr2); var_dump($intersect);
Step 2: Use the array_diff() function to remove duplicate values from the two arrays ( Intersection elements)
Use the array_diff() function to compare the two arrays and the intersection array respectively to obtain the difference set (remove duplicate values and obtain non-duplicate elements).
$diff1=array_diff($arr1,$intersect); $diff2=array_diff($arr2,$intersect); echo "删除交集元素后的两数组:"; var_dump($diff1); var_dump($diff2);
Compare:
Description:
array_diff() function is used Compares the values of two (or more) arrays and returns the difference.
This function compares the values of two (or more) arrays (value in key=>value), and Returns a difference array that includes all values in the compared array (array1) but not in any other parameter array (array2).
Recommended learning: "PHP Video Tutorial 》
The above is the detailed content of How to remove duplicate values from two arrays in php. For more information, please follow other related articles on the PHP Chinese website!