牛骨文教育服务平台(让学习变的简单)
博文笔记

php for循环的坑,千万不要在判断条件中使用count

创建时间:2015-11-23 投稿人: 浏览次数:124

引用php manual 中的例子:

<?php
/*
 * This is an array with some data we want to modify
 * when running through the for loop.
 */
$people = array(
    array(
"name" => "Kalle""salt" => 856412),
    array(
"name" => "Pierre""salt" => 215863)
);

for(
$i 0$i count($people); ++$i) {
    
$people[$i]["salt"] = mt_rand(000000999999);
}
?>

上面这段代码中,每次循环都得计算count,很显然这个会非常影响速度,所以最好将count放到循环外部。

<?php
$people 
= array(
    array(
"name" => "Kalle""salt" => 856412),
    array(
"name" => "Pierre""salt" => 215863)
);

for(
$i 0$size count($people); $i $size; ++$i) {
    
$people[$i]["salt"] = mt_rand(000000999999);
}
?>

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。