Home > Article > Backend Development > How to delete array intersection in php
In PHP, deleting array intersection is a common task. Intersection is the values that are common in two or more arrays. In some cases, we may need to remove intersections from one or more arrays in order to perform a specific operation or comparison on them. This article will introduce several methods, along with their pros and cons, to help you accomplish this task.
Method 1: Use the array_diff function
PHP has a built-in function called array_diff, which can return elements in one array that exist in another or multiple arrays. We can use this function to remove the intersection between two or more arrays.
$arr1 = array(1, 2, 3, 4, 5); $arr2 = array(3, 4, 5, 6, 7); $result = array_diff($arr1, $arr2); print_r($result); // [1, 2]
In the above example, we use the array_diff function to obtain the elements in $arr1 that do not exist in $arr2. This means the intersection has been removed.
Advantages:
Disadvantages:
Method 2: Use foreach loop
Another method is to use foreach loop. The idea of this method is to loop through the first array and check if each of its elements is present in other arrays. If present, the element is removed from the first array.
$arr1 = array(1, 2, 3, 4, 5); $arr2 = array(3, 4, 5, 6, 7); foreach ($arr1 as $key => $value) { if (in_array($value, $arr2)) { unset($arr1[$key]); } } print_r($arr1); // [1, 2]
In the above example, we use foreach to loop through $arr1 and use the in_array function to check whether the current element exists in $arr2. If present, use the unset function to remove the element from $arr1.
Advantages:
Disadvantages:
Method 3: Use the array_filter function
Another method is to use the array_filter function. This function filters elements in an array based on a set of rules. We can define a callback function that checks if each element in the array exists in other arrays. If present, the element is removed.
$arr1 = array(1, 2, 3, 4, 5); $arr2 = array(3, 4, 5, 6, 7); $callback = function($value) use ($arr2) { return !in_array($value, $arr2); }; $result = array_filter($arr1, $callback); print_r($result); // [1, 2]
In the above example, we use the array_filter function and a callback function to get the elements in $arr1 that are not present in $arr2. The callback function uses a use statement to pass $arr2 to it.
Advantages:
Disadvantages:
To sum up, if you only need to remove the intersection between two arrays, using the array_diff function is the fastest. If you need to remove intersections from multiple arrays, using a foreach loop or array_filter function is a better option. Depending on your needs, choose the most appropriate method to complete the task.
The above is the detailed content of How to delete array intersection in php. For more information, please follow other related articles on the PHP Chinese website!