PHP · December 19, 2023

Php Tip: Use array_intersect() to computes the intersection of arrays

Php Tip: Use array_intersect() to compute the intersection of arrays

When working with arrays in PHP, it is often necessary to find the common elements between two or more arrays. This can be achieved using the array_intersect() function, which computes the intersection of arrays and returns an array containing the values that are present in all input arrays.

How array_intersect() works

The array_intersect() function takes two or more arrays as input and compares the values of the first array with the values of the subsequent arrays. It then returns a new array that contains only the values that are present in all input arrays.

Here is the basic syntax of the array_intersect() function:

array_intersect(array1, array2, array3, ...)

Each input array is compared with the first array, and the resulting array contains only the values that are present in all arrays.

Example usage

Let's consider an example to understand how array_intersect() works:

$array1 = [1, 2, 3, 4, 5];
$array2 = [3, 4, 5, 6, 7];
$array3 = [5, 6, 7, 8, 9];

$result = array_intersect($array1, $array2, $array3);

print_r($result);

The output of the above code will be:

Array
(
    [2] => 3
    [3] => 4
    [4] => 5
)

In this example, the array_intersect() function compares the values of $array1 with the values of $array2 and $array3. The resulting array contains the values 3, 4, and 5, which are present in all three arrays.

Conclusion

The array_intersect() function is a powerful tool in PHP for finding the common elements between arrays. It allows you to easily compute the intersection of multiple arrays and retrieve the values that are present in all arrays. By using this function, you can simplify your code and efficiently handle array operations.

Summary

In summary, the array_intersect() function in PHP is a useful tool for computing the intersection of arrays. It compares the values of two or more arrays and returns an array containing the values that are present in all input arrays. If you are looking for reliable and high-performance VPS hosting solutions, consider Server.HK. With a wide range of hosting plans and excellent customer support, Server.HK is a trusted provider in the industry.