PHP function introduction: array_intersect() function
In PHP, the array_intersect() function is used to compare the values of two or more arrays and return a new An array containing all values present in the input array.
Syntax
array_intersect(array1,array2,array3...)
Parameters
Return value
Returns an array that contains all values that exist in the input array.
Examples
Here are some examples of the array_intersect() function:
Example 1:
$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 )
Example 2:
$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 )
Example 3:
$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 )
Explanation
In example 1, $array1 contains "apple", " There are four elements: "banana", "orange" and "grape". $array2 contains three elements: "banana", "mango" and "grape". After comparing two arrays through the array_intersect() function, the resulting array contains values that exist in both arrays, namely "banana" and "grape".
In Example 2, $array1 contains the numbers 1 to 5, and $array2 contains the numbers 4 to 7. After comparison through the array_intersect() function, the resulting array contains the values that exist in both arrays, namely 4 and 5.
In Example 3, $array1, $array2 and $array3 contain different color values. After the array_intersect() function compares three arrays, the resulting array contains only color values that exist in all three arrays, namely "green" and "blue".
Summary
The array_intersect() function is a very commonly used function in PHP, which can easily compare and extract common elements in multiple arrays. By rationally using this function, we can handle array-related logical issues more easily and improve development efficiency.
The above is the detailed content of PHP function introduction: array_intersect() function. For more information, please follow other related articles on the PHP Chinese website!