Instance
Compares the key values of two arrays and returns the intersection:
<?php$a1=array ("A" = "red", "b" = "green", "c" = "Blue", "d" = "yellow"), $a 2=array ("e" = "red", "f" = > "Green", "g" = "blue"), $result =array_intersect ($a 1, $a 2);p Rint_r ($result);? >
Definition and usage
The Array_intersect () function is used to compare the key values of two (or more) arrays and return the intersection.
The function compares the key values of two (or more) arrays and returns an array of intersections that contain all the key values in the array being compared (array1), as well as in any other parameter array (array2 or array3, and so on).
Grammar
Array_intersect (Array1,array2,array3 ...);
Parameters |
Describe |
Array1 |
Necessary. The first array to compare with the other array. |
Array2 |
Necessary. The array to compare with the first array. |
Array3,... |
Optional. The other array to compare to the first array. |
Technical details
return value: |
Returns an array of intersections that contain all the key values in the array being compared (array1), as well as in any other parameter array (array2 or array3, and so on). |
PHP version: |
4.0.1+ |
More examples
Example 1
Compares the key values of three arrays and returns the intersection:
<?php$a1=array ("A" = "red", "b" = "green", "c" = "Blue", "d" = "yellow"), $a 2=array ("e" = "red", "f" = > "Black", "G" and "purple"); $a 3=array ("a" = "red", "b" = "BLACK", "h" = "yellow"); $result =array_ Intersect ($a 1, $a 2, $a 3);p Rint_r ($result);? >
When using the Array_intersect () function, it is important to note that the Array_intersect () function considers them to be the same only if the two elements are equal and has the same data type, otherwise the intersection calculation cannot occur. The Array_intersect () function returns an array that retains the key, consisting only of the values appearing in the first array and appearing in the other arrays.
If you require the intersection of associative arrays, use the ARRAY_INTERSECT_ASSOC () function to give you a simple example:
<?php$fruit1 = Array ("Red" = "Apple", "yellow" = "Banana", "orange" = "orange"), $fruit 2 = Array ("Yellow" = > "Pear", "Red" and "Apple", "Purple" and "Grape"); $fruit 3 = Array ("green" = "watermelon", "orange" + "orange" "Red" = "Apple"), $intersection = Array_intersect_assoc ($fruit 1, $fruit 2, $fruit 3);p Rint_r ($intersection);//output: Array ([red] = Apple)?>
The syntax format for the ARRAY_INTERSECT_ASSOC () function is as follows:
Array Array_intersect_assoc (array Array1,array array2[,arrayn ...])