Home > php教程 > php手册 > body text

PHP两种去掉数组重复值的方法比较

WBOY
Release: 2016-06-06 20:21:19
Original
1211 people have browsed it

这篇文章主要介绍了PHP两种去掉数组重复值的方法比较,分别是foreach方法和array_unique方法,需要的朋友可以参考下

去除一个数组中的重复值,可以使用foreach方法,也可以使用array_unique方法,下面的代码两种方法都使用了。

"; $intStart1 = time(); $arrRS = array_unique($arrT); $intEnd2 = time(); $intTime2 = $intEnd2-$intStart1; echo "With array_unique function,Spend time:($intTime2)"; echo "

";
print_r($arrT);
print_r($arrRF);
print_r($arrRS);
echo "
Copy after login
"; ?>

在$intTotal比较小的情况下,比如说1000以内,$intRand的取值基本不影响结果,两者执行的时间都差不多。

测试$intTotal 大于10000时,,$intRand取值100时,使用array_unique的效率要高于foreach循环判断,$intRand=10,两者执行时间一致。

因此,可以得出结论,当数组容量不大,大概在1000以内时,使用两者的执行效率差不多。

当数组容量比较大时(具体应该到什么值,我没有详细测试,感兴趣的可以确定一下这个值),随着$intRand的逐渐增大,array_unique的表现更好,我不使用$intTotal/$intRand这个比值,是因为,感觉并不是成比例变化,但是基本会遵循比值越大,array_unique表现越好。

综上所述,在过滤数组重复值的时候,建议使用array_unuique,数组不大的时候两者效率等同,而array_unique使用当然让你的代码一下子减了好几行,数组容量过大时,函数的表现更好,为什么不用呢?

Related labels:
php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!