百科狗-知识改变命运!
--

array_intersect() - 计算数组的交集 - php 数组函数

是丫丫呀1年前 (2023-11-21)阅读数 26#技术干货
文章标签数组

array_intersect()

array_intersect() - 计算数组的交集 - php 数组函数

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

计算数组的交集

说明

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

array_intersect()返回一个数组,该数组包含了所有在$array1中也同时出现在所有其它参数数组中的值。注意键名保留不变。

参数

$array1

要检查的数组,作为主值。

$array2

要被对比的数组。

要对比的数组列表。

返回值

返回一个数组,该数组包含了所有在$array1中也同时出现在所有其它参数数组中的值。

范例

Example #1array_intersect()例子

以上例程会输出:

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

注释

Note:两个单元仅在(string)$elem1 ===(string)$elem2时被认为是相同的。也就是说,当字符串的表达是一样的时候。

参见

  • array_intersect_assoc() 带索引检查计算数组的交集
  • array_diff() 计算数组的差集
  • array_diff_assoc() 带索引检查计算数组的差集
A clearer example of the key preservation of this function:

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.
Here is a array_union($a, $b): 
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);
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. 
Note that array_intersect and array_unique doesnt work well with multidimensional arrays.
If you have, for example, 

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:

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

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

showing us who bought the same thing today and yesterday =)
[]s
Take care of value types while using array_intersect function as there is no option for strict type check as in in_array function.
$array1 = array(true,2);
$array2 = array(1, 2, 3, 4, 5, 6);
var_dump(array_intersect($array1, $array2));
result is :
array(2) {
    [0] => bool(true)
    [1] => int(2)
}
Using isset to achieve this, is many times faster:

Results:
Array
(
  [1] => 2
  [3] => 4
  [5] => 6
  [7] => 8
  [9] => 10
)
Took 4.7170009613037
(
  [0] => 2
  [1] => 4
  [2] => 6
  [3] => 8
  [4] => 10
)
Took 0.056024074554443
array_intersect: 4.717
array_flip+isset: 0.056
This function is able to sort an array based on another array that contains the order of occurrence. The values that are not present will be transferred into the end of the resultant.
Questa funzione permette di ordinare i valori di un array ($tosort) basandosi sui valori contenuti in un secondo array ($base), i valori non trovati verranno posizionati alla fine dell'ordinamento senza un'ordine specifico. 
The built-in function returns wrong result when input arrays have duplicate values.
Here is a code that works correctly: 
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:

This will return:
Array ( [first] => 2 [third] => 3 )
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: 
Regarding array union: Here is a faster version array_union($a, $b)
But it is not needed! See below.
 
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
I wrote this function to recursively replace array keys with array values (flip) and fill values with defined value. it can be used for recursive array intersect functions . 
If you have to intersect arrays of unique values then using array_intersect_key is about 20 times faster, just have to flip the key value pairs of the arrays, then flip the result again.

Did it in 0.89163708686829 seconds.
Did it in 0.038213968276978 seconds.
$x = array('ram@hb.in', 'ram', 'rams@hb.in');
  $y = array('1231231231');
  $result=array_intersect($x,$z);
  $res = array_intersect($y, $z);
Also note that, even without the availability of the strict mode switch, false does not match 0:
array_intersect([false], [0]) == [];
Even in PHP 7.1
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:

You can try this out with this: 
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: 
I used array_intersect in order to sort an array arbitrarly:

...which could be useful for constructing an SQL query, or some other situation where testing for them one by one might be too clumsy.
To check whether an array $a is a subset of array $b, do the following:

Actually, PHP ought to have a function that does this for you. But the above example works.
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. 
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..

Barış ÇUHADAR
189780@gmail.com
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  Where $smallerArray is the array with lesser items. I only tested this with long strings but I would imagine that it is somewhat universal.
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.
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. 
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:

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.
Just a small mod to ben's code to make it work properly:

This is useful for checking for illegal characters in a username.
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"]
array_intersect($array1, $array2);
returns the same as:
array_diff($array1, array_diff($array1, $array2));
I ran into a problem (PHP 5.6) with array_intersect(), though i had no idea it was it at the time : using it properly created an array to string conversion notice, through this type of code (and with both array variables verified) :

Rewriting its supposed behaviour, even in a rather simple way, removed the notice. Not sure what caused the function to be unhappy but here's my code that works properly : 
If you just need confirmation that there intersection (and will not use the return of the intersection). Just only returns a boolean.

In this case, the return is true.
Just a handy tip. 
If you want to produce an array from two seperate arrays on their intersects, here you go:

Gives you:
/branches/E_SHOP/Webdirectory_1_0
$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
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. 
I needed an array_intersect that would delete the intersecting values from the original array. Voila: 
this one will work with associative arrays. also an overwrite function to only replace those elements in the first array. 
The reason that this function is considerably slow; is because it's comparing not only the values cross wise; but it also compares the array's own elements too.
For example you have two arrays like;

Intersection will start to compare from the first three colors like; "blue" to "green", "black" to "blue"; that are, the elements of the first array only, and yes, comparison order is arbitrary, but always in the same order.
It will do the same for the second array too.

鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com

免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)

图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)