In PHP, the array_intersect() function is used to compare the values of two or more arrays and return a new array containing the values that exist in all the input arrays.
array_intersect(array1, array2, array3...)
array1: Required. The base array to compare from.
array2: Required. The array to compare against array1.
array3,...: Optional. Additional arrays to compare.
Returns an array containing the values that are present in all the input arrays. The keys from array1 are preserved.
Below are some common usage scenarios for array_intersect():
$array1 = array("apple", "banana", "orange", "grape"); $array2 = array("banana", "mango", "grape"); $result = array_intersect($array1, $array2); print_r($result);
Output:
Array ( [1] => banana [3] => grape )
$array1 = array(1, 2, 3, 4, 5); $array2 = array(4, 5, 6, 7); $result = array_intersect($array1, $array2); print_r($result);
Output:
Array ( [3] => 4 [4] => 5 )
$array1 = array("red", "green", "blue"); $array2 = array("green", "blue", "yellow"); $array3 = array("blue", "yellow", "pink"); $result = array_intersect($array1, $array2, $array3); print_r($result);
Output:
Array ( [1] => green [2] => blue )
In practical development, array_intersect() is widely used in data filtering, permission matching, tag comparison, and other scenarios. For instance, when you need to find common elements from multiple sources of data, this function can help you achieve that easily and effectively.
array_intersect() is a highly useful function in PHP that allows you to quickly identify common elements between arrays. By leveraging this function effectively, developers can improve efficiency in array data processing and simplify their code logic.