PHP array_intersect() Function
Quick summary: The PHP array_intersect() function computes the intersection of arrays using values.
PHP array_intersect() Syntax
array_intersect(array $array, array ...$arrays): array
PHP
PHP array_intersect() Basic examples
var_dump(array_intersect([1,2,3], [2,3,4]));
PHP
Output:
array(2) {
[1]=> int(2)
[2]=> int(3)
}
Returns values common to both arrays.
PHP array_intersect() Real-world usage
$userRoles = ['admin','editor'];
$allowed = ['editor','viewer'];
var_dump(array_intersect($userRoles, $allowed));
PHP
Output:
array(1) {
[1]=> string(6) "editor"
}
Checks access permissions.
PHP array_intersect() Edge cases
var_dump(array_intersect([], [1,2]));
PHP
Output:
array(0) {
}
Intersecting with an empty array returns an empty array.
PHP array_intersect() Common mistakes
Expecting reindexed keys
array_intersect preserves keys from the first array.
Incorrect
array_intersect([1,2,3],[2]);
Correct
array_values(array_intersect([1,2,3],[2]));
Reindex manually if needed.
PHP array_intersect() Frequently Asked Questions
What does array_intersect() do in PHP?
array_intersect() returns values present in all given arrays.
Does array_intersect() preserve keys?
Yes, it preserves keys from the first array.
Is array_intersect() case-sensitive?
Yes, comparisons are case-sensitive.
Does array_intersect() compare keys?
No, it compares only values.
Can array_intersect() handle multiple arrays?
Yes, it can compare more than two arrays.
Does array_intersect() modify arrays?
No, it returns a new array.
What is the difference from array_diff()?
array_intersect() finds common values, while array_diff() finds differences.
Can array_intersect() work with associative arrays?
Yes, but only values are compared.
What happens with duplicates?
Duplicates are preserved if present in the first array.
Is array_intersect() fast?
Performance depends on array size.
Use case of array_intersect()?
Finding common elements between datasets.
Can it be combined with array_map()?
Yes, often used together for data processing.
PHP array_intersect() Related PHP Functions
-
array_allLearn more about array_all
-
array_anyLearn more about array_any
-
array_change_key_caseLearn more about array_change_key_case
-
array_chunkLearn more about array_chunk
-
array_intersect_assoc PHP examplesLearn more about array_intersect_assoc PHP examples
-
array_intersect_key PHP examplesLearn more about array_intersect_key PHP examples