?php$s = '';for($i=1;$i=1000000;$i ){$r = rand(1000000,9999999);$s .= $r.',';}$a = explode(',',$s);$t1 =microtime(true);for($i=0;$i100;$i ){$t = rand(1,1000000);if(in_array($a[$t],$a)){}}$t2 = microtime(true);$b = array_flip($a);for($i=0
<?php $s = ''; for($i=1;$i<=1000000;$i++){ $r = rand(1000000,9999999); $s .= $r.','; } $a = explode(',',$s); $t1 =microtime(true); for($i=0;$i<100;$i++){ $t = rand(1,1000000); if(in_array($a[$t],$a)){} } $t2 = microtime(true); $b = array_flip($a); for($i=0;$i<100;$i++){ $t = rand(1,1000000); if(isset($a[$t],$b)){} } $t3 = microtime(true); $c = array_flip($a); for($i=0;$i<100;$i++){ $t = rand(1,1000000); if(array_key_exists($a[$t],$c)){} } $t4 = microtime(true); echo $t2-$t1; echo "\r\n"; echo $t3-$t2; echo "\r\n"; echo $t4-$t3; echo "\r\n";
time php -f test.php 运行结果如下
8.6652669906616
0.43561315536499
0.67533493041992
real?? ?0m14.255s
user?? ?0m11.990s
sys?? ?0m0.380s
原文地址:如何快速判断一个值是否在数组中, 感谢原作者分享。