Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Array Functions : array_intersect

array_intersect

Computes the intersection of arrays (PHP 4 >= 4.0.1, PHP 5)
array array_intersect ( array array1, array array2 [, array ...] )

Example 253. array_intersect() example

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

The above example will output:

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

Related Examples ( Source code ) » array_intersect



Code Examples / Notes » array_intersect

ben

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.


aaron

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;
}
?>


anbolb

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.


david

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.


blu

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


tompittlik

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.


drew

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


tom p

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"
?>


sapenov

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);


"inerte" is my hotmail.com username

If you have a slow database query that uses JOIN, try to array_intersect() the table records.
I hung up my server countless times before using this function. Simple select from one table and put the records in an array ($records_1), then select records from any other table and put them in another array($records_2).
array_intersect() will emulate a JOIN for you.
<?php
$emulated_join = array_intersect($records_1, $records_2);
?>
Remember to test if it really offers a speed improvement, your mileage may vary (database type, hardware, version, etc...)
You could also emulate a JOIN from two text files, reading each line with the file() function.


t dot wiltzius

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 )


nthitz

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.

terry -at- shuttleworths -dot- net

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.


niels

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
?>


alessandro ranellucci alex

array_intersect($array1, $array2);
returns the same as:
array_diff($array1, array_diff($array1, $array2));


sets intersection

$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


Change Language


Follow Navioo On Twitter
array_change_key_case
array_chunk
array_combine
array_count_values
array_diff_assoc
array_diff_key
array_diff_uassoc
array_diff_ukey
array_diff
array_fill_keys
array_fill
array_filter
array_flip
array_intersect_assoc
array_intersect_key
array_intersect_uassoc
array_intersect_ukey
array_intersect
array_key_exists
array_keys
array_map
array_merge_recursive
array_merge
array_multisort
array_pad
array_pop
array_product
array_push
array_rand
array_reduce
array_reverse
array_search
array_shift
array_slice
array_splice
array_sum
array_udiff_assoc
array_udiff_uassoc
array_udiff
array_uintersect_assoc
array_uintersect_uassoc
array_uintersect
array_unique
array_unshift
array_values
array_walk_recursive
array_walk
array
arsort
asort
compact
count
current
each
end
extract
in_array
key
krsort
ksort
list
natcasesort
natsort
next
pos
prev
range
reset
rsort
shuffle
sizeof
sort
uasort
uksort
usort
eXTReMe Tracker