判断某字符是否包含与某于数组中,方法有很多,刚学习php的新手们估计偏向于使用循环来解决,对于一般的小网站来说,这种解决方案是不会出现什么大问题的。但就性能来说,这种方法不是最好的方法,下面笔者就 foreach,in_array() array_search 这三种方法来比较这三种方法在性能表现上的差异。
<?php
$runtime= new runtime;
$runtime->start();
 $a = 'k';
 $b = array('a','b','c','d','e','f','g','h','i','j','k');
/*
for ($i=0; $i < 100000; $i++) {
 var_dump(in_array($a, $b)); 
}
*/
/*
for ($i=0; $i < 100000; $i++) {
 foreach ($b as $key => $value) {
 if ($a == $value) {
 //echo TRUE;
 continue;
 }
 }
}
*/
/*
for ($i=0; $i < 100000; $i++) {
 array_search($a, $b);
}
*/
$runtime->stop();
echo $_b;
echo "执行时间: ".$runtime->spent()." 毫秒";
class runtime{
 var $StartTime = 0;
 var $StopTime = 0;
 function get_microtime(){
 list($usec, $sec) = explode(' ', microtime());
 return ((float)$usec + (float)$sec);
 }
 function start(){
 $this->StartTime = $this->get_microtime();
 }
 function stop(){
 $this->StopTime = $this->get_microtime();
 }
 function spent(){
 return round(($this->StopTime - $this->StartTime) * 1000, 1);
 }
}
?>以上程序执行时间如下图所示:
in_array()

foreach

array_search()

由上可以大致看出这三种方法在性能上的表现了吧,array_search 和 in_array 表现差不多,foreach 表现最差。