Home > Article > Backend Development > How to determine whether two arrays have duplicate elements in PHP
php can use the "array_intersect()" function to determine whether there are duplicate elements in two arrays. The operation method is: 1. Create a PHP sample file; 2. Define two arrays "array1" and "array2" Contain some elements respectively; 3. Use the "array_intersect()" function to pass in the two arrays as parameters, and store the results in the variable "$intersection"; 4. Check whether the variable "$intersection" is empty.
Operating system for this tutorial: Windows 10 system, php8.1.3 version, Dell G3 computer.
In PHP, you can use the array_intersect() function to determine whether there are duplicate elements in two arrays. The array_intersect() function accepts two arrays as parameters and returns a new array containing the common elements between the two input arrays.
If the new array returned by array_intersect() is not empty, it means that there are duplicate elements in the two arrays.
The following is a sample code that demonstrates how to determine whether there are duplicate elements in two arrays:
<?php $array1 = array(1, 2, 3, 4, 5); $array2 = array(4, 5, 6, 7, 8); intersection=arrayintersect(intersection = array_intersect(intersection=arrayintersect(array1, $array2); if (!empty($intersection)) { echo "两个数组存在重复元素"; } else { echo "两个数组不存在重复元素"; } ?>
In the above example, we defined two arrays array1 and array2, each containing some elements. We then use the array_intersect() function passing the two arrays as arguments to it, storing the returned result in the variable $intersection .
Finally, we use the empty() function to check whether $intersection is empty. If it is not empty, it will output "there are duplicate elements in the two arrays", otherwise it will output "there are no duplicate elements in the two arrays".
The above is the detailed content of How to determine whether two arrays have duplicate elements in PHP. For more information, please follow other related articles on the PHP Chinese website!