Home > php教程 > php手册 > php array_diff用法详解

php array_diff用法详解

WBOY
Release: 2016-06-21 08:53:15
Original
1209 people have browsed it

array_diff计算数组的差集

说明

array array_diff ( array $array1 , array $array2 [, array $ ... ] )

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>
Copy after login

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

Note: 注意本函数只检查了多维数组中的一维。当然可以用 array_diff($array1[0], $array2[0]); 检查更深的维度。

Warning

本函数在 PHP 4.0.4 中是坏的!



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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template