Definition and Usage
- PHP Version
- 4.0.1+
The array_intersect() function returns an array containing values from the base array that also exist in one or more other arrays.
This function is used to compare common values across arrays and is typically applied in the following situations.
- Finding values that exist in both arrays
- Checking whether a user-provided value already exists
- Filtering data that appears simultaneously across multiple data sources
Features
- This function finds common elements between arrays based on their values, not their keys. It uses loose comparison (
==), so values are considered equal even if their data types differ, as long as their contents match. - The keys of the returned array are preserved exactly as they appear in the base array.
Basic Example
To fully understand how the array_intersect() function works,
it is helpful to examine the following three scenarios:
- Comparing Indexed Arrays
- Comparing Associative Arrays
- Comparing an Indexed Array with an Associative Array
Comparing Indexed Arrays
/* Comparing indexed arrays */
$index_array1 = [1, 2, 3, 4, 5]; // Base array for comparison
$index_array2 = [2, 3, 4, 6, 7];
$index_unique_value = array_intersect($index_array1, $index_array2);
print_r($index_unique_value);
Array
(
[1] => 2
[2] => 3
[3] => 4
)
Comparing Associative Arrays
/* Comparing associative arrays */
$assoc_array1 = [ // Base array for comparison
'a' => 'apple',
'b' => 'banana',
'c' => 'carrot',
'd' => 'date'
];
$assoc_array2 = [
'x' => 'carrot',
'b' => 'grape',
'y' => 'apple'
];
$assoc_unique_value = array_intersect($assoc_array1, $assoc_array2);
print_r($assoc_unique_value);
Array
(
[a] => apple
[c] => carrot
)
Comparing an Indexed Array with an Associative Array
/* Comparing an indexed array with an associative array */
$arr_idx = ['a', 'b', 'c']; // Base array for comparison
$arr_assoc = [
'x' => 'b',
'y' => 'c',
'z' => 'd'
];
$assoc_unique_value = array_intersect($arr_idx, $arr_assoc);
print_r($assoc_unique_value);
Array
(
[1] => b
[2] => c
)
Syntax
array_intersect(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
Returns an array containing the values that exist in both the base array and one or more other arrays.
The keys of the returned array are preserved from the base array. However, if the base array is an indexed array (an array with numeric keys only), the keys are reindexed starting from 0.
If no common values are found between the base array and the other arrays, an empty array is returned.
$array1 = [1, 2, 3, 4, 5];
$array2 = [6, 7];
$result = array_intersect($array1, $array2);
print_r($result); // Array ( )
Changes as of PHP 8.0.0
As of PHP 8.0.0, the array_intersect() 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 = [1, 2, 2, 3, 4, 4, 5];
$intersect = array_intersect($array);
print_r($intersect);
// As of PHP 8.0.0, it is possible to pass only a single array
/* Output:
Array
(
[0] => 1
[1] => 2
[2] => 2
[3] => 3
[4] => 4
[5] => 4
[6] => 5
)
*/
Looking at the example above, $uniqueValues returns the entire $array without any changes.
This is because the array_intersect() function is designed to find the intersection of at least two arrays. When only a single array is passed, there is no other array to compare against, so the function simply returns the array itself. To compute an actual intersection, at least two arrays must be provided.
If you want to return duplicate values from a single array, you can do so as follows.
$array = [1, 2, 2, 3, 4, 4, 5];
$counts = array_count_values($array);
$duplicates = array_filter($counts, function($count) {
return $count > 1;
});
print_r(array_keys($duplicates)); // Array ( [0] => 2 [1] => 4 )
In the code above, the array_count_values() function is used to count how many times each value appears in the array. Then, array_filter() is used to extract values whose count is greater than 1.
Finally, array_keys() is used to return an array containing only the duplicated values.
Using this approach, duplicate values within a single array can be retrieved.
Things to Keep in Mind
Let's take a look at some important points to keep in mind when using the array_intersect() function.
Comparing Keys and Values in Associative Arrays
The array_intersect() function compares values only, not keys.
As a result, when working with associative arrays, values are treated as common values even if their keys are different. This behavior can lead to some important considerations when using associative arrays.
$array1 = ['a' => 1, 'b' => 2, 'c' => 3];
$array2 = ['x' => 1, 'y' => 2, 'z' => 3];
$result = array_intersect($array1, $array2);
print_r($result); // Output: Array ( [a] => 1 [b] => 2 [c] => 3 )
In the code above, the array_intersect() function compares only the values and returns the matching values from $array1, preserving its original keys.
Even though the keys in $array2 are different, values that match are included in the result array.
If you need to find values where both the key and the value match, use the array_intersect_assoc() function instead.
Ignoring Data Types When Comparing Array Values
The array_intersect() function compares values only and does not take data types into account. In other words, even if the data types differ, values are considered equal if their contents match. The following example illustrates this behavior.
$array1 = [1, 2, '3']; // '3' is a string
$array2 = [1, 2, 3]; // 3 is an integer
$result = array_intersect($array1, $array2);
print_r($result); // Output: Array ( [0] => 1 [1] => 2 [2] => 3 )
In the example above, $array1 and $array2 both contain the values '3' and 3, but their data types are different.
The array_intersect() function compares values using loose comparison (==), which means it does not distinguish between different data types. As a result, values with different data types but the same content are considered equal and included in the result array.
Practical Examples
The array_intersect() function can be applied in a variety of real-world scenarios. Below are several practical examples that demonstrate how this function is commonly used.
Extracting Duplicate Data from a Database
The array_intersect() function makes it easy to find common values between an array retrieved from a database and another selected array.
$userIdsFromDatabase = [1, 2, 3, 4, 5];
$selectedUserIds = [2, 4, 6, 8, 10];
$commonUserIds = array_intersect($userIdsFromDatabase, $selectedUserIds);
print_r($commonUserIds); // Array ( [1] => 2 [3] => 4 )
In this example, common user IDs are extracted by comparing the array of user IDs retrieved from the database with the array of selected user IDs. This approach is useful when handling duplicate IDs across different data sources.
Validating Form Input
This function is useful for checking whether values submitted by a user through a form belong to a predefined set of allowed values.
$submittedTags = ['php', 'javascript', 'html'];
$allowedTags = ['html', 'css', 'javascript', 'python'];
$validTags = array_intersect($submittedTags, $allowedTags);
print_r($validTags); // Array ( [2] => javascript [1] => html )
In this example, common values between the submitted tag array and the allowed tag array are extracted to perform form input validation.
User Permission Management
By using array_intersect(), you can determine the common permissions between an administrator’s permission set and a user’s actual permissions.
$adminPermissions = ['read', 'write', 'delete', 'update'];
$userPermissions = ['read', 'write'];
$allowedPermissions = array_intersect($adminPermissions, $userPermissions);
print_r($allowedPermissions); // Array ( [0] => read [1] => write )
In this example, common permissions between the administrator and the user are identified, allowing you to determine the maximum permissions the user is allowed to have.
Product Inventory Management
This function is also useful in inventory management scenarios, where you need to find products that are both selected by the user and actually in stock.
$availableProducts = ['product1', 'product2', 'product3', 'product4'];
$selectedProducts = ['product2', 'product4', 'product5'];
$inStockProducts = array_intersect($availableProducts, $selectedProducts);
print_r($inStockProducts); // Array ( [1] => product2 [3] => product4 )
In this example, common values between the available product list and the selected product list are extracted to identify products that can actually be purchased.
By using the array_intersect() function, you can effectively manage and utilize common values between arrays across a wide range of practical scenarios.
References
See also
- PHP array_intersect_assoc() Function – Finding Common Elements with Another Array Based on Key–Value Pairs
- PHP array_diff() Function – Finding Array Differences by Value
- PHP array_diff_assoc() Function – Comparing Array Differences by Key–Value Pairs
- 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