Home > Article > Backend Development > How to get intersection (key comparison) using array_intersect_key function in PHP
In PHP, array is an extremely common data type. In practical applications, we often need to perform some operations on arrays, such as searching, sorting, filtering, etc. Among them, taking intersection is a relatively common operation. The array_intersect_key() function provided in PHP can be used to intersect two or more arrays (key comparison), that is, return the keys and values that exist in all given arrays.
array_intersect_key() function is used as follows:
array array_intersect_key( array $array1 , array $array2 [, array $... ] )
This function accepts two or more array parameters. It returns a new array containing a number of key-value pairs present in all arrays, indexed by the keys of the first argument array. Each parameter array can contain any number of key-value pairs, which are used to determine intersection.
Let’s look at a simple example:
$array1 = array('a' => 'apple', 'b' => 'banana', 'c' => 'coconut'); $array2 = array('b' => 'banana', 'c' => 'coconut', 'd' => 'date'); $result = array_intersect_key($array1, $array2); print_r($result);
The output result of the above code is:
Array ( [b] => banana [c] => coconut )
As you can see, only the key b is retained in the $result array and elements of c. This is because these two elements appear in both $array1 and $array2.
The following are some notes on this function:
The above is an introduction to the array_intersect_key() function in PHP. Using this function you can easily get the intersection from multiple arrays without the need for complex comparison operations. I hope this article can help you use arrays in PHP more effectively.
The above is the detailed content of How to get intersection (key comparison) using array_intersect_key function in PHP. For more information, please follow other related articles on the PHP Chinese website!