Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Array Functions

PHP array_intersect() function

Reference for PHP array_intersect(): find values present in every array, how keys are kept, string comparison rules and the assoc and user-callback variants.

array_intersect() returns the values of the first array that also exist in all of the other arrays. It is the opposite of array_diff(): where diff removes what matches, intersect keeps only what matches.

The keys of the first array are preserved, and so is its order. Values are compared by their string form, which is the same rule array_diff() uses.

PHP
<?php
print_r(array_intersect([1, 2, 3, 4], [2, 4, 6]));
// [1 => 2, 3 => 4]

Try it

PHP Common values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP String comparison and variants

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
array_intersect(array $array, array ...$arrays): array
Name Description
$array The array whose values are tested. Its keys and order are kept.
...$arrays Arrays to compare against. A value must appear in every one of them.

Return value: an array with the entries of $array whose value is present in all other arrays. Empty if there are none.

Usage notes

  • Comparison uses strings: two values match when (string) $a === (string) $b. That is why 1, "1" and 1.0 all match each other.
  • Keys are kept. The result often has gaps in its keys. Wrap it in array_values() if you want a list.
  • Order and duplicates come from the first array. If the first array contains a matching value twice, both entries stay.
  • Performance: for big arrays, flip one array and test with isset() or use array_intersect_key() on flipped arrays. That runs in linear time, while array_intersect() sorts internally.
  • Variants: array_intersect_assoc() also compares keys, array_intersect_key() compares only keys, and array_uintersect() uses your own comparison callback (it must return a negative number, zero or a positive number).
  • Nested arrays cannot be compared this way. They convert to the string "Array" with a warning.
  • A single argument is allowed and returns a copy of the array.