array_intersect

(PHP 4 >= 4.0.1, PHP 5)

array_intersectComputes the intersection of arrays

Descrierea

array array_intersect ( array $array1 , array $array2 [, array $... ] )

array_intersect() returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved.

Parametri

array1

The array with master values to check.

array2

An array to compare values against.

...

A variable list of arrays to compare.

Valorile întoarse

Returns an array containing all of the values in array1 whose values exist in all of the parameters.

Exemple

Example #1 array_intersect() example

<?php
$array1 
= array("a" => "green""red""blue");
$array2 = array("b" => "green""yellow""red");
$result array_intersect($array1$array2);
print_r($result);
?>

Exemplul de mai sus va afișa:

Array
(
    [a] => green
    [0] => red
)

Note

Notă: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.

Vedeți de asemenea

add a note add a note

User Contributed Notes 32 notes

up
27
stuart at horuskol dot co dot uk
6 years ago
A clearer example of the key preservation of this function:

<?php

$array1
= array(2, 4, 6, 8, 10, 12);
$array2 = array(1, 2, 3, 4, 5, 6);

var_dump(array_intersect($array1, $array2));
var_dump(array_intersect($array2, $array1));

?>

yields the following:

array(3) {
  [0]=> int(2)
  [1]=> int(4)
  [2]=> int(6)
}

array(3) {
  [1]=> int(2)
  [3]=> int(4)
  [5]=> int(6)
}

This makes it important to remember which way round you passed the arrays to the function if these keys are relied on later in the script.
up
7
sapenov at gmail dot com
9 years ago
If you need to supply arbitrary number of arguments
to array_intersect() or other array function,
use following function:

$full=call_user_func_array('array_intersect', $any_number_of_arrays_here);
up
10
Niels
8 years ago
Here is a array_union($a, $b):

<?php
                                       
//  $a = 1 2 3 4
   
$union =                            //  $b =   2   4 5 6
       
array_merge(
           
array_intersect($a, $b),    //         2   4
           
array_diff($a, $b),         //       1   3
           
array_diff($b, $a)          //               5 6
       
);                              //  $u = 1 2 3 4 5 6
?>
up
2
terry(-at-)shuttleworths(-dot-)net
8 years ago
I couldn't get array_intersect to work with two arrays of identical objects, so I just did this:

foreach ($firstarray as $key=>$value){
    if (!in_array($value,$secondarray)){
        unset($firstarray[$key]);
    }
}

This leaves $firstarray as the intersection.

Seems to work fine & reasonably quickly.
up
1
ben at kazez dot com
11 years ago
To check whether an array $a is a subset of array $b, do the following:

<?php
if(array_unique($b + $a) === $b)
//...
?>

Actually, PHP ought to have a function that does this for you. But the above example works.
up
1
dml at nm dot ru
3 years ago
The built-in function returns wrong result when input arrays have duplicate values.
Here is a code that works correctly:

<?php
function array_intersect_fixed($array1, $array2) {
   
$result = array();
    foreach (
$array1 as $val) {
      if ((
$key = array_search($val, $array2, TRUE))!==false) {
        
$result[] = $val;
         unset(
$array2[$key]);
      }
    }
    return
$result;
}
?>
up
1
Esfandiar -- e.bandari at gmail dot com
6 years ago
Regarding array union:  Here is a faster version array_union($a, $b)

But it is not needed!  See below.

<?php
                                       
//  $a = 1 2 3 4
   
$union =                            //  $b =   2   4 5 6
       
array_merge(
           
$a,   
           
array_diff($b, $a)          //               5 6
       
);                              //  $u = 1 2 3 4 5 6
?>

You get the same result with $a + $b.

N.B. for associative array the results of $a+$b and $b+$a are different, I think array_diff_key is used.

Cheers, E
up
2
Yohann
4 years ago
I used array_intersect in order to sort an array arbitrarly:

<?php
$a
= array('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'height', 'nine', 'ten');
$b = array('four', 'one', 'height', 'five')
var_dump(array_intersect($a, $b);
?>

will output:

0 => 'one'
1 => 'four'
2 => 'five'
3 => 'height'

i hope this can help...
up
1
gary
5 years ago
i wrote this one to get over the problem i found in getting strings intersected instead of arrays as there is no function in php.

<?php
function matched_main_numbers($string, $string2)
{
$string = "04 16 17 20 29";
$arr1 = explode(" ", $string);

$string2 = "45 34 04 29 16";
$arr2 = explode(" ", $string2);

$array = array_intersect($arr1, $arr2);
$comma_separated = implode($array);

$str = $comma_separated;

$balls = "$comma_separated";
$matched_balls = chunk_split($balls,2," ");
$matched_balls =" $matched_balls";

$number_of_matched_main_balls = strlen($str);
$number_of_matched_main_balls = ($number_of_matched_main_balls/2);
$numbers = "You matched $number_of_matched_main_balls main balls";

return
$numbers;
       
}
?>
up
1
tim at zeroedin dot com
10 months ago
Note... this function does not seem intuitive for doing intersection of flat arrays, in the sense that an intersection are common values between. This is an issue if you are doing a for loop over the results of an intersect function, as shown below, wherein the for loop iterates over something different depending on order.

Below is example of a function whioch I think works correctly,  the output from original function, and new function.

function array_value_mutual_intersection($array1, $array2)
{
    $hashMap = array();
    $output = array();
    foreach($array1 as $item)
        $hashMap[$item] = '';
    foreach($array2 as $item)
        if(isset($hashMap[$item]))
            array_push($output, $item);
    return $output;
}

$a = ['one', 'two', 'three', 'four'];
$b = ['three', 'two'];

echo "Original array a = " . json_encode($a) . "\n";
echo "Original array b = " . json_encode($b) . "\n";

echo "PHP array_intersect says interesection of (a,b) is: " . json_encode(array_intersect($a,$b)) . "\n";
echo "PHP array_intersect says interesection of (b,a) is: " . json_encode(array_intersect($b,$a)) . "\n\n";

echo "My intersect function says intersection of (a,b) is: " . json_encode(array_value_mutual_intersection($a, $b)) . "\n";
echo "My intersect function says intersection of (b,a) is: " . json_encode(array_value_mutual_intersection($b, $a)) . "\n\n";

-------output------

$ php test.php
Original array a = ["one","two","three","four"]
Original array b = ["three","two"]
PHP array_intersect says interesection of (a,b) is: {"1":"two","2":"three"}
PHP array_intersect says interesection of (b,a) is: ["three","two"]

My intersect function says intersection of (a,b) is: ["three","two"]
My intersect function says intersection of (b,a) is: ["two","three"]
up
1
meihao at 126 dot com
1 year ago
<?php
$a
=array(1,2,'3',4);
$b=array('1',2,3);

var_dump($a,$b);

result:
array (
size=3)
 
0 => int 1
  1
=> int 2
  2
=> string '3' (length=1)

?>
up
0
Mike Block
1 year ago
I bench-marked some uses of array_intersect and can't believe how slow it is. This isn't as elaborate, but handles most cases and is much faster:

<?php
/**
examines two arrays and returns the intersected arrays with matching keys (ignores duplicate keys)
*/
function simple_array_intersect($a,$b) {
   
$a_assoc = $a != array_values($a);
   
$b_assoc = $b != array_values($b);
   
$ak = $a_assoc ? array_keys($a) : $a;
   
$bk = $b_assoc ? array_keys($b) : $b;
   
$out = array();
    for (
$i=0;$i<sizeof($ak);$i++) {
        if (
in_array($ak[$i],$bk)) {
            if (
$a_assoc) {
               
$out[$ak[$i]] = $a[$ak[$i]];
            } else {
               
$out[] = $ak[$i];
            }
        }
    }
    return
$out;
}

?>

You can try this out with this:

<?php
// create a large array (simple)
$first = array();
for (
$i=500;$i<500000;$i++) {
   
$first[] = $i;
}
// create a smaller array (associative)
$second = array();
for (
$i=499990;$i<500000;$i++) {
   
$second[$i] = rand();
}
echo
microtime(true)."\n";
// built-in function
print_r(array_intersect($first,$second));
echo
microtime(true)."\n";
// favour simple array as match
print_r(simple_array_intersect($first,$second));
echo
microtime(true)."\n";
// favour associative keys for match
print_r(simple_array_intersect($second,$first));
echo
microtime(true)."\n";

?>
up
0
caffinated
2 years ago
If you're looking for a relatively easy way to strictly intersect keys and values recursively without array key reordering, here's a simple recursive function:

<?php
function array_intersect_recursive($array1, $array2)
{
  foreach(
$array1 as $key => $value)
  {
    if (!isset(
$array2[$key]))
    {
      unset(
$array1[$key]);
    }
    else
    {
      if (
is_array($array1[$key]))
      {
       
$array1[$key] = array_intersect_recursive($array1[$key], $array2[$key]);
      }
      elseif (
$array2[$key] !== $value)
      {
        unset(
$array1[$key]);
      }
    }
  }
  return
$array1;
}
?>
up
0
Oto Brglez
5 years ago
If you wish to create intersection with arrays that are empty. Than the result of intersection is empty array.

If you wish to change this. I sugest that you do this.
It simply "ignores" empty arrays. Before loop use 1st array.

<?php

$a
= array();
$a[] = 1;
$a[] = 2;
$a[] = 3;

$b = array();
$b[] = 4;
$b[] = 5;
$b[] = 1;

$c = array();
$c[] = 1;
$c[] = 5;
$d = array();

$kb=array('a','b','c','d');

$out = $a;
foreach(
$kb as $k){
    if(!empty(${
$k})) $out = array_intersect($out,${$k});
};
print_r($out);
// The result is array

// The result is empty array
print_r(array_intersect($a,$b,$c,$d));

?>
up
0
karl at libsyn dot com
5 years ago
Given a multidimensional array that represents AND/OR relationships (example below), you can use a recursive function with array_intersect() to see if another array matches that set of relationships. 

For example: array( array( 'red' ), array( 'white', 'blue' ) ) represents "red OR ( white AND blue )".  array( 'red', array( 'white', 'blue' ) ) would work, too, BTW.

If I have array( 'red' ) and I want to see if it matches the AND/OR array, I use the following function.  It returns the matched array,
but can just return a boolean if that's all you need:

<?php
$needle
= array( array( 'red' ), array( 'white', 'blue' ) );
$haystack = array( 'red' );

function
findMatchingArray( $needle, $haystack ) {
    foreach(
$needle as $element ) {
       
$test_element = (array) $element;
        if(
count( $test_element ) == count( array_intersect( $test_element, $haystack ) ) ) {
            return
$element;
        }

    }
    return
false;
}
?>

Pretty tough to describe what I needed it to do, but it worked.  I don't know if anyone else out there needs something like this, but hope this helps.
up
0
Malte
6 years ago
Extending the posting by Terry from 07-Feb-2006 04:42:

If you want to use this function with arrays which have sometimes the same value several times, it won't be checked if they're existing in the second array as much as in the first.
So I delete the value in the second array, if it's found there:

<?php
$firstarray
= array(1, 1, 2, 3, 4, 1);
$secondarray = array(4, 1, 6, 5, 4, 1);

//array_intersect($firstarray, $secondarray): 1, 1, 1, 4

foreach ($firstarray as $key=>$value){
    if (!
in_array($value,$secondarray)){
        unset(
$firstarray[$key]);
    }else{
        unset(
$secondarray[array_search($value,$secondarray)]);
    }
}

//$firstarray: 1, 1, 4

?>
up
0
blu at dotgeek dot org
10 years ago
Note that array_intersect and array_unique doesnt work well with multidimensional arrays.
If you have, for example,

<?php

$orders_today
[0] = array('John Doe', 'PHP Book');
$orders_today[1] = array('Jack Smith', 'Coke');

$orders_yesterday[0] = array('Miranda Jones', 'Digital Watch');
$orders_yesterday[1] = array('John Doe', 'PHP Book');
$orders_yesterday[2] = array('Z da Silva', 'BMW Car');

?>

and wants to know if the same person bought the same thing today and yesterday and use array_intersect($orders_today, $orders_yesterday) you'll get as result:

<?php

Array
(
    [
0] => Array
        (
            [
0] => John Doe
           
[1] => PHP Book
       
)

    [
1] => Array
        (
            [
0] => Jack Smith
           
[1] => Coke
       
)

)

?>

but we can get around that by serializing the inner arrays:
<?php

$orders_today
[0] = serialize(array('John Doe', 'PHP Book'));
$orders_today[1] = serialize(array('Jack Smith', 'Coke'));

$orders_yesterday[0] = serialize(array('Miranda Jones', 'Digital Watch'));
$orders_yesterday[1] = serialize(array('John Doe', 'PHP Book'));
$orders_yesterday[2] = serialize(array('Z da Silva', 'Uncle Tungsten'));

?>

so that array_map("unserialize", array_intersect($orders_today, $orders_yesterday)) will return:

<?php

Array
(
    [
0] => Array
        (
            [
0] => John Doe
           
[1] => PHP Book
       
)

)

?>

showing us who bought the same thing today and yesterday =)

[]s
up
0
t dot wiltzius at insightbb dot com
10 years ago
I needed to compare an array with associative keys to an array that contained some of the keys to the associative array. Basically, I just wanted to return only a few of the entries in the original array, and the keys to the entries I wanted were stored in another array. This is pretty straightforward (although complicated to explain), but I couldn't find a good function for comparing values to keys. So I wrote this relatively straightforward one:

<?php

function key_values_intersect($values,$keys) {
   foreach(
$keys AS $key) {
     
$key_val_int[$key] = $values[$key];
      }
   return
$key_val_int;
   }

$big = array("first"=>2,"second"=>7,"third"=>3,"fourth"=>5);
$subset = array("first","third");

print_r(key_values_intersect($big,$subset));

?>

This will return:

Array ( [first] => 2 [third] => 3 )
up
0
anbolb at boltblue dot com
10 years ago
This is also handy for testing an array for one of a series of acceptable elements. As a simple example, if you're expecting the query string to contain one of, say, user_id, order_id or item_id, to find out which one it is you could do this:

<?php
    $valid_ids
= array ('user_id', 'item_id', 'order_id');
    if (
$id = current (array_intersect ($valid_ids, array_keys ($_GET))))
    {
       
// do some stuff with it
   
}
    else
       
// error - invalid id passed, or none at all
?>

...which could be useful for constructing an SQL query, or some other situation where testing for them one by one might be too clumsy.
up
-2
juliotorres1604 at hotmail dot com
1 year ago
<?php
// Function to intersect n arrays

function getIntersect($arrays){
       
$totalArrays = count($arrays);
        if(
$totalArrays >= 2){
               
$arrayTmp $arrays[0];
                for (
$i = 1; $i < $totalArrays; $i++) {
                   
$arrayTmp = array_intersect($arrayTmp, $arrays[$i]);
                }
                return
$arrayTmp;
        }else{
            return
FALSE;
        }
    }

// Example:
$arrayTmp[0] = array('0'=>0, '1'=>7, '2'=>5);
$arrayTmp[1] = array('0'=>7, '1'=>5, '2'=>0, '3'=>15);
$arrayTmp[2] = array('0'=>3, '1'=>0, '2'=>7, '3'=>4);

$intersectArray = getIntersect($arrayTmp);
print_r($arrayFinal);
?>

The above example will output:

Array
(
    [0] => 0
    [1] => 7
)
up
0
david at audiogalaxy dot com
13 years ago
Note that array_intersect() considers the type of the array elements when it compares them.

If array_intersect() doesn't appear to be working, check your inputs using var_dump() to make sure you're not trying to intersect an array of integers with an array of strings.
up
-1
nthitz at gmail dot com
8 years ago
I did some trials and if you know the approximate size of the arrays then it would seem to be a lot faster to do this <?php array_intersect($smallerArray, $largerArray); ?> Where $smallerArray is the array with lesser items. I only tested this with long strings but I would imagine that it is somewhat universal.
up
-1
189780 at gmail dot com
4 years ago
Actually array_intersect finds the dublicate values, here is my approach which is 5 times faster than built-in function array_intersect().. Give a try..

<?php
function my_array_intersect($a,$b)
{
        for(
$i=0;$i<sizeof($a);$i++)
        {
               
$m[]=$a[$i];
        }
        for(
$i=0;$i<sizeof($a);$i++)
        {
               
$m[]=$b[$i];
        }
       
sort($m);
       
$get=array();
        for(
$i=0;$i<sizeof($m);$i++)
        {
                if(
$m[$i]==$m[$i+1])
               
$get[]=$m[$i];
        }
        return
$get;
}
?>

Barış ÇUHADAR
189780@gmail.com
up
-1
Shawn Pyle
5 years ago
array_intersect handles duplicate items in arrays differently. If there are duplicates in the first array, all matching duplicates will be returned. If there are duplicates in any of the subsequent arrays they will not be returned.

<?php
array_intersect
(array(1,2,2),array(1,2,3)); //=> array(1,2,2)
array_intersect(array(1,2,3),array(1,2,2)); //=> array(1,2)
?>
up
-1
tom p
9 years ago
If you store a string of keys in a database field and want to match them to a static array of values, this is a quick way to do it without loops:

<?

$vals
= array("Blue","Green","Pink","Yellow");
$db_field = "0,2,3";

echo
implode(", ", array_flip(array_intersect(array_flip($vals), explode(",", $db_field))));

// will output "Blue, Pink, Yellow"

?>
up
-1
tompittlik at disfinite dot net
10 years ago
Just a small mod to ben's code to make it work properly:

<?php

if(sort(array_unique($b + $a)) === sort($b))
// $a is legit
}

?>

This is useful for checking for illegal characters in a username.
up
-1
SETS INTERSECTION
9 years ago
$a = array(1,2,3,4,5,2,6,1);  /* repeated elements --> $a is not a set */
$b = array(0,2,4,6,8,5,7,9,2,1);  /* repeated elements --> $b is not a set */

$ua = array_merge(array_unique($a));  /* now, $a is a set */
$ub = array_merge(array_unique($b));  /* now, $b is a set */

$intersect = array_merge(array_intersect($ua,$ub));

Note: 'array_merge' removes blank spaces in the arrays.
Note: order doesn't matter.

In one line:

$intersect_a_b = array_merge(array_intersect(array_merge(array_unique($a)), array_merge(array_unique($b))));

Additions/corrections wellcome...

gRiNgO
up
-1
drew at iws dot co dot nz
9 years ago
Just a handy tip.

If you want to produce an array from two seperate arrays on their intersects, here you go:

<?

$a
= array("branches","E_SHOP");
$b = array("E_SHOP","Webdirector_1_0");

print
join("/",array_merge(array_diff($a, $b), array_intersect($a, $b), array_diff($b, $a)));

?>

Gives you:

/branches/E_SHOP/Webdirectory_1_0
up
-1
Alessandro Ranellucci alex at primafila dot net
11 years ago
array_intersect($array1, $array2);
returns the same as:
array_diff($array1, array_diff($array1, $array2));
up
-3
faharanik
4 years ago
Here's my approach to intersection returning only the values present in all the arrays.
Note that each array must not contain duplicate values.
I don't know how effective it actually is, but perhaps it could help.

<?php
// $arrays - Array of arrays to intersect.

function calculate_intersection($arrays)
    {
   
$intersection = Array();
               
    for(
$checked_item = 0; $checked_item < count($arrays[0]); $checked_item++)
        {
       
$occurrence = 1;
       
        for(
$compared_array = 1; $compared_array < count($arrays); $compared_array++)
            {           
            for(
$compared_item = 0; $compared_item < count($arrays[$compared_array]); $compared_item++)
                {
                if(
$arrays[0][$checked_item] == $arrays[$compared_array][$compared_item])
                    {
                   
$occurrence++;

                    if(
$occurrence == count($arrays))
                        {
                       
$intersection[] = $arrays[0][$checked_item];
                        }
                    }
                }
            }
        }
   
    return
$intersection;
    }
?>
up
-2
james -at- bandit.co -dot- nz
4 years ago
I needed an array_intersect that would delete the intersecting values from the original array. Voila:

<?php
// array_intersect that splits the needle array into two - one filled with "intersected" results, and one filled with the remainder
function array_intersect_split(&$needle, $haystack, $preserve_keys = false) {
    if(!
is_array($needle) || !is_array($haystack)) return false;
   
$new_arr = array();
    foreach(
$needle as $key => $value) {
        if((
$loc = array_search($value, $haystack))!==false) {
            if(!
$preserve_keys) $new_arr[] = $value;
            else
$new_arr[$key] = $value;
            unset(
$needle[$key]);
        }
    }
    return
$new_arr;
}
?>
up
-2
aaron
8 years ago
this one will work with associative arrays.  also an overwrite function to only replace those elements in the first array.

<?php

function array_union()
{
    if (
func_num_args() < 2) { return; }
   
$arrays = func_get_args();
   
$outputArray = array_shift($arrays);
   
$remaining = count($arrays);
    for (
$i=0; $i<$remaining; $i++)
    {
       
$nextArray = $arrays[$i];
        foreach (
$nextArray as $key=>$value)
        {
           
$outputArray[$key] = $value;
        }
    }
    return
$outputArray;
}

function
array_overwrite()
{
    if (
func_num_args() < 2) { return; }
   
$arrays = func_get_args();
   
$outputArray = array_shift($arrays);
   
$remaining = count($arrays);
    for (
$i=0; $i<$remaining; $i++)
    {
       
$nextArray = $arrays[$i];
        foreach (
$nextArray as $key=>$value)
        {
            if (
array_key_exists($key, $outputArray)) {    $outputArray[$key] = $value; }
        }
    }
    return
$outputArray;
}

?>
To Top