array_diff — 计算数组的差集
array_diff() 返回一个数组,该数组包括了所有在 array1 中但是不在任何其它参数数组中的值。注意键名保留不变。
Example #1 array_diff() 例子
<span style="color: rgb(0,0,0)"><font face="NSimsun"><span style="color: rgb(0,0,187)"><?php <br/>
$array1 </span><span style="color: rgb(0,119,0)">= array(</span><span style="color: rgb(221,0,0)">"a" </span><span style="color: rgb(0,119,0)">=> </span><span style="color: rgb(221,0,0)">"green"</span><span style="color: rgb(0,119,0)">, </span><span style="color: rgb(221,0,0)">"red"</span><span style="color: rgb(0,119,0)">, </span><span style="color: rgb(221,0,0)">"blue"</span><span style="color: rgb(0,119,0)">, </span><span style="color: rgb(221,0,0)">"red"</span></font><font face="NSimsun"><span style="color: rgb(0,119,0)">);<br></span><span style="color: rgb(0,0,187)">$array2 </span><span style="color: rgb(0,119,0)">= array(</span><span style="color: rgb(221,0,0)">"b" </span><span style="color: rgb(0,119,0)">=> </span><span style="color: rgb(221,0,0)">"green"</span><span style="color: rgb(0,119,0)">, </span><span style="color: rgb(221,0,0)">"yellow"</span><span style="color: rgb(0,119,0)">, </span><span style="color: rgb(221,0,0)">"red"</span></font><font face="NSimsun"><span style="color: rgb(0,119,0)">);<br></span><span style="color: rgb(0,0,187)">$result </span><span style="color: rgb(0,119,0)">= </span><span style="color: rgb(0,0,187)">array_diff</span><span style="color: rgb(0,119,0)">(</span><span style="color: rgb(0,0,187)">$array1</span><span style="color: rgb(0,119,0)">, </span><span style="color: rgb(0,0,187)">$array2</span></font><font face="NSimsun"><span style="color: rgb(0,119,0)">);<br><br></span><span style="color: rgb(0,0,187)">print_r</span><span style="color: rgb(0,119,0)">(</span><span style="color: rgb(0,0,187)">$result</span></font><font face="NSimsun"><span style="color: rgb(0,119,0)">);<br></span><span style="color: rgb(0,0,187)">?></span>
</font></span>
在 $array1 中多次出现的值一样处理,输出结果为:
Array<br/>(<br/> [1] => blue<br/>)<br/>
Note: 两个单元仅在 (string) $elem1 === (string) $elem2 时被认为是相同的。也就是说,当字符串的表达是一样的时候。
WarningNote: 注意本函数只检查了多维数组中的一维。当然可以用 array_diff($array1[0], $array2[0]); 检查更深的维度。
《PHP技术内幕》中文版查看详情本书详细说明了PHP的使用方法,内容涉及PHP应用的各个方面,并提供了大量的代码实例,使读者能够快速而容易地学会PHP。每一章都分为两部分,前一部分“深入分析”详细说明相关的技术信息,
385
![]()
立即学习“PHP免费学习笔记(深入)”;
本函数在 PHP 4.0.4 中是坏的!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号