Home > Backend Development > PHP Tutorial > Implementation examples of simple intersection, difference and union functions of PHP arrays

Implementation examples of simple intersection, difference and union functions of PHP arrays

黄舟
Release: 2023-03-16 20:52:02
Original
1732 people have browsed it

The example of this article describes the PHP implementation of simple intersection, difference, and union functions for 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:

The above is the detailed content of Implementation examples of simple intersection, difference and union functions of PHP 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