Definition and Usage
- PHP Version
- 4.3+
The array_intersect_assoc() function
compares whether arrays have common elements based on key–value pairs (intersection),
and returns an associative (associative) array consisting of elements from the first array that also exist in the other array.
This function is used to find elements that exist in common with another array by checking whether both the key and the value match at the same time in associative arrays. In other words, an element is considered common only when both its key and value are identical.
By using this behavior, you can identify elements that must be kept in common across multiple associative arrays based on specific key–value combinations.
This function is mainly used for the following purposes:
- Finding common elements whose keys and values are both identical in another array
- Checking the intersection of associative arrays
- Extracting only the common elements from associative arrays based on specific key–value pairs
Basic Example
/* Find elements where both the key and value pairs are identical in another array */
$array1 = ['a' => 1, 'b' => 2, 'c' => 3]; // The base array used for comparison
$array2 = ['b' => 2, 'c' => 3, 'd' => 4];
$result = array_intersect_assoc($array1, $array2);
print_r($result); // Array ( [b] => 2 [c] => 3 )
/* Check the intersection between associative arrays */
$current_user_info = ['id' => 1, 'name' => 'John', 'age' => 30];
$updated_user_info = ['id' => 1, 'name' => 'John', 'age' => 31];
$common = array_intersect_assoc($updated_user_info, $current_user_info);
if (!empty($common)) {
echo 'There is data that remains consistent: ';
foreach ($common as $key => $value) {
echo $key . ': ' . $value . ' ';
}
} else {
echo 'No common data found.';
}
// Output: There is data that remains consistent: id: 1 name: John
/* Extract only the common elements based on specific key–value pairs */
$original_array = ['id' => 1, 'name' => 'John', 'age' => 30];
$criteria = ['name' => 'John'];
$result = array_intersect_assoc($original_array, $criteria);
print_r($result); // Array ( [name] => John )
The array_intersect_assoc() function
finds elements that exist in another array
based on whether both the key (Key) and value (Value) match at the same time.
In contrast, the
array_intersect()
function compares values only, without considering keys (Key),
and is used to find values that also exist in another array.
| Function | Difference |
|---|---|
array_intersect_assoc() |
Compares both the keys and values of the arrays. |
array_intersect() |
Compares values only, without considering array keys. |
Syntax
array_intersect_assoc(array $array_1, $array_2, $array_3, ...): array
Parameters
$array_1 |
Required. The array used as the base for comparison. |
|---|---|
$array_2 |
Required (optional as of PHP 8.0.0). An array to compare against the first array.
See Changes as of PHP 8.0.0. |
$array_3, ... |
Optional. Additional arrays to compare against the first array. Multiple arrays can be provided. |
Return Values
The function compares arrays to determine whether key–value pairs match at the same time across two or more arrays, and returns a new associative array consisting of the key–value pairs from the first array that also exist in the other arrays.
If no elements from the first array match based on both the key (Key) and value (Value), an empty array is returned.
$array1 = ["a" => 1, "b" => 2, "c" => 3];
$array2 = ["b" => 3, "c" => 4, "d" => 5];
$common_elements = array_intersect_assoc($array1, $array2);
print_r($common_elements); // Array ( )
Changes as of PHP 8.0.0
As of PHP 8.0.0, the array_intersect_assoc() function can be called with only a single parameter. Previously, at least two parameters were required.
- Before PHP 8.0.0, at least two arrays always had to be passed as parameters.
- As of PHP 8.0.0, it is possible to pass only a single array.
$array = ["a" => 1, "b" => 2, "c" => 3];
$result = array_intersect_assoc($array);
print_r($result);
/* Output:
Array
(
[a] => 1
[b] => 2
[c] => 3
)
*/
Things to Keep in Mind
The array_intersect_assoc() function is used to find elements that exist in common (intersection) with another array based on matching key–value pairs.
When Data Types Differ but String Representations Are the Same
When comparing arrays, keys (Key) are compared based on identity according to PHP array rules, while values (Value) are compared using loose comparison. As a result, differences in data types are not distinguished during value comparison.
$array1 = ['a' => 1, 'b' => 2, 'c' => '3']; // '3' is stored as a string
$array2 = ['a' => 1, 'b' => 2, 'c' => 3]; // 3 is stored as an integer
$intersect = array_intersect_assoc($array1, $array2);
print_r($intersect);
/* Output:
Array
(
[a] => 1
[b] => 2
[c] => 3
)
*/
In the code above, $array1 and $array2 both contain the values
'3' and 3, but under loose comparison,
these two values are considered equal.
As a result, the array_intersect_assoc() function does not distinguish between the data type differences
and treats the element as a common match, including it in the result array.
String Representations Must Match
Even if the data types are different, values are treated as identical when their string representations are the same.
However, the array_intersect_assoc() function compares values by first converting each element to a string (string) and then performing a string-based comparison.
In other words, even when the data types differ, the values are considered a match only if their forms are identical after being converted to strings.
$array1 = array(0, 1, 2); // Integers 0, 1, 2
$array2 = array('00', '01', '2'); // Strings '00', '01', '2'
$result = array_intersect_assoc($array1, $array2);
print_r($result);
/* Output:
Array
(
[2] => 2
)
*/
In the example above, when converted to strings, 0 and 1 become '0' and '1', which are different from '00' and '01', and are therefore identified as mismatches.
However, the integer 2 becomes the string '2', which matches the string '2', and is therefore identified as a common element.
Practical Examples
This function is commonly used for the following purposes:
- Data searching and filtering
- Checking whether data matches
- Handling related data
Data Searching and Filtering
When working with multiple data arrays, you can search or filter data by identifying elements in which specific keys and values exist in common.
Assume that you have arrays containing product information, and that the user has selected certain filter criteria. The following example demonstrates how to find products that match the user-selected filters.
$products = [
['id' => 1, 'name' => 'Laptop', 'brand' => 'Dell', 'price' => 1200],
['id' => 2, 'name' => 'Smartphone', 'brand' => 'Samsung', 'price' => 800],
['id' => 3, 'name' => 'Tablet', 'brand' => 'Apple', 'price' => 600],
['id' => 4, 'name' => 'Smartwatch', 'brand' => 'Fitbit', 'price' => 150],
];
// Filter criteria selected by the user
$filter_criteria = ['brand' => 'Samsung', 'price' => 800];
// Find products that match the selected criteria
$filtered_products = [];
foreach ($products as $product) {
if (count(array_intersect_assoc($product, $filter_criteria)) === count($filter_criteria)) {
$filtered_products[] = $product;
}
}
// Output the result
print_r($filtered_products);
/*
Array
(
[0] => Array
(
[id] => 2
[name] => Smartphone
[brand] => Samsung
[price] => 800
)
)
*/
Additional Explanation
The count() function counts all elements in the given array and returns the result as an integer.
As shown in the result above, the product that matches the user-selected filter criteria is returned as an array.
Because a product with the brand 'Samsung' and a price of 800 exists, that product is included in the result array.
Checking Whether Data Matches
This function can be used to check whether specific keys and values match simultaneously across two or more arrays.
The following example checks whether two arrays contain identical keys and values.
// Information for two users
$user_1 = [
'id' => 1,
'username' => 'john_doe',
'email' => 'john@example.com',
'age' => 30,
];
$user_2 = [
'id' => 2,
'username' => 'jane_smith',
'email' => 'jane@example.com',
'age' => 28,
];
// Function to check whether matching keys and values exist
function has_matching_info($user_1, $user_2) {
$matching_info = array_intersect_assoc($user_1, $user_2);
// Return true if matching key–value pairs exist
return !empty($matching_info);
}
// Output the result
if (has_matching_info($user_1, $user_2)) {
echo 'There is matching information between the two users.';
} else {
echo 'There is no matching information between the two users.';
}
// Output: 'There is no matching information between the two users.'
In this code, each user's information is represented as an array.
The has_matching_info() function is used to determine whether identical keys and values exist between the two arrays,
and a message is displayed based on the result.
Handling Related Data
When multiple data arrays contain related keys and values at the same time, you can use this function as a basis for processing or manipulating the data.
The following example checks whether two users prefer the same programming languages based on their preference data.
// Programming language preferences of user 1
$user1_languages = [
'Python' => 4,
'JavaScript' => 5,
'Java' => 3,
];
// Programming language preferences of user 2
$user2_languages = [
'JavaScript' => 5,
'Java' => 4,
'PHP' => 2,
];
// Function to find matching language preferences
function find_matching_languages($languages1, $languages2) {
$matching_languages = array_intersect_assoc($languages1, $languages2);
return $matching_languages;
}
// Output the result
$matching_languages = find_matching_languages($user1_languages, $user2_languages);
if (!empty($matching_languages)) {
echo 'Both users prefer the same programming languages. ('
. implode(', ', array_keys($matching_languages)) . ')';
} else {
echo 'The two users do not share the same programming language preferences.';
}
// Output: Both users prefer the same programming languages. (JavaScript)
Additional Explanation
The implode() returns a string created by joining the elements of an array in order, separated by a specified delimiter.
Additional Explanation
The array_keys() function extracts only the keys from a given array and returns them as a new array.
In this example, the find_matching_languages() function is used to identify programming languages that both users prefer.
Based on the result, the code determines whether the users share common preferences.
This example demonstrates how related data can be compared and processed using associative arrays.
References
See also
- PHP array_diff() Function – Finding Array Differences by Value
- PHP array_diff_assoc() Function – Comparing Array Differences by Key–Value Pairs
- PHP array_intersect() Function – Finding Common Values Between Arrays
- PHP array_filter() Function – Filter Elements with a Callback
- PHP array_values() Function – Get a List of Array Values
- PHP array_search() Function – Searching for a Value in an Array