时间:2021-07-01 10:21:17 帮助过:19人阅读
For 循环
While 循环
Foreach 循环
for循环用于已经确定将你的表达式需要执行多少次的情况。
语法:
for (initialization; condition; increment)
{
code to be executed;
}<?php
for($i=1; $i<=100000; $i++)
{
echo "The number is " . $i . "<br>";
}
?>while表达式将会执行一段代码直到条件语句为false。While循环通常更适合数据库相关操作。
语法:
while (condition)
{
code to be executed;
}<?php
// If you had an array with fruit names and prices in you could use foreach
$fruit = array(
"orange" =--> "5.00",
"apple" => "2.50",
"banana" => "3.99"
);
foreach ($fruit as $key => $value)
{
"$key is $value dollars";
}
?>我们知道在PHP中有多种循环,现在我们需要知道哪种循环更加高效,以便于我们编写的应用更快。
下面我们开始实验进行对比.
<?php
// While Loop
$a=0;
while($a < 1000)
{
$a++;
}
?>VS.
<?php
// For Loop
for($a = 0; $a < 1000;)
{
$a++;
}
?>上述实验证明While循环比For循环执行效率要高出19.71%。因此,推荐尽可能的使用while循环而不是For循环。
<?php
$test = array(1 => "cat", "dog" => 0, "red" => "green", 5 => 4, 3, "me");
$keys = array_keys($test);
$size = sizeOf($keys);
for($a = 0; $a < $size; $a++)
{
$t = $test[$keys[$a]];
}
?>VS.
<?php
$test = array(1 => "cat", "dog" => 0, "red" => "green", 5 => 4, 3, "me");
foreach($test as $t)
{
}
?>上述实验证明Foreach 循环比For循环快141.29%!
这些循环通常用于实现不同的目的,现在我们知道了各个循环在执行效率上的表现。当需要追求执行效率的时候,我们通常推荐使用while循环来代替for循环。同样的在foreach循环和loop循环之间,尽可能的使用foreach循环。下一步,我们将会研究如何有效地在模板中使用循环。请继续关注。
以上就是php中For、While、Foreach的对比说明的详细内容,更多请关注Gxl网其它相关文章!