PHP implements simple intersection, difference and union examples of arrays

小云云
Release: 2023-03-19 11:00:01
Original
2176 people have browsed it

This article mainly introduces PHP to implement simple intersection, difference, and union functions of arrays, including the usage skills of PHP array operation functions array_diff, array_intersect, and array_merge. Friends who need it can refer to it. I hope it can help everyone.

The example in this article describes the PHP implementation of simple intersection, difference, and union functions of arrays. Share it with everyone for your reference, the details are as follows:


<?php
$arr1 = array(
&#39;0&#39; => &#39;zero&#39;,
&#39;1&#39; => &#39;one&#39;,
&#39;2&#39; => &#39;two&#39;,
&#39;3&#39; => &#39;three&#39;
);
$arr2 = array(
&#39;2&#39; => &#39;two&#39;,
&#39;three&#39; => &#39;three&#39;,
&#39;4&#39; => &#39;four&#39;,
&#39;5&#39; => &#39;five&#39;
);
//差集【对比返回在 arr1 中但是不在 arr2 及任何其它参数数组中的值。】
$array_diff = array_diff($arr1,$arr2); 
echo "<pre class="brush:php;toolbar:false">"; print_r($array_diff);
/* 输出结果
*Array
*(
* [0] => zero
* [1] => one
*)
*/
//交集【对比返回既在 arr1 中也在 arr2 数组中的值。】
# 注意事项: 键值保留arr1数组中的键值不变
$array_intersect = array_intersect($arr1,$arr2); 
echo "<pre class="brush:php;toolbar:false">"; print_r($array_intersect);
/* 输出结果
*Array
*(
* [2] => two
* [3] => three
*)
*/
//并集【将arr1数组中的值附加在arr2数组的后面。返回作为结果的数组。 】
#注意事项:【如果输入的数组中有相同的字符串键名,则该键名后面的值将覆盖前一个值。
#然而,如果数组包含数字键名,后面的值将不会覆盖原来的值,而是附加到后面。】
$array_merge = array_merge($arr1,$arr2); 
echo "<pre class="brush:php;toolbar:false">"; print_r($array_merge);
/* 输出结果
* Array
* (
* [0] => zero
* [1] => one
* [2] => two
* [3] => three
* [4] => two
* [three] => three
* [5] => four
* [6] => five
* )
*/
?>
Copy after login

Running results:

Related recommendations:

Union, intersection and difference functions of arrays

php function array_intersect_uassoc()# that compares the key names and key values ​​of two arrays and returns the intersection

##An example of simple intersection, difference and union functions of php arrays

The above is the detailed content of PHP implements simple intersection, difference and union examples of arrays. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template