for 循环 vs while 循环 vs foreach 循环 PHP
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12847502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
for loop vs while loop vs foreach loop PHP
提问by Techie
1st off I'm new to PHP. I have been using for loop,while loop,foreach loop in scripts. I wonder
第一次关闭我是 PHP 的新手。我一直在脚本中使用 for 循环、while 循环、foreach 循环。我想知道
- which one is better for performance?
- what's the criteria to select a loop?
- which should be used when we loop inside another loop?
- 哪个性能更好?
- 选择循环的标准是什么?
- 当我们在另一个循环中循环时应该使用哪个?
the code which I'm stuck with wondering which loop to be used.
我一直想知道要使用哪个循环的代码。
for($i=0;$i<count($all);$i++)
{
//do some tasks here
for($j=0;$j<count($rows);$j++)
{
//do some other tasks here
}
}
It's pretty obvious that I can write the above code using while. Hope someone will help me out to figure out which loop should be better to be used.
很明显,我可以使用 while 编写上述代码。希望有人能帮助我弄清楚应该更好地使用哪个循环。
回答by Pekka
which one is better for performance?
哪个性能更好?
It doesn't matter.
没关系。
what's the criteria to select a loop?
选择循环的标准是什么?
If you just need to walk through all the elements of an object or array, use foreach. Cases where you needforinclude
如果您只需要遍历对象或数组的所有元素,请使用foreach. 您需要的情况for包括
- When you explicitly need to do things with the numeric index, for example:
- when you need to use previous or next elements from within an iteration
- when you need to change the counter during an iteration
- 当您明确需要对数字索引执行操作时,例如:
- 当您需要在迭代中使用上一个或下一个元素时
- 当您需要在迭代期间更改计数器时
foreachis much more convenient because it doesn't require you to set up the counting, and can work its way through any kind of member - be it object properties or associative array elements (which a forwon't catch). It's usually best for readability.
foreach更方便,因为它不需要您设置计数,并且可以通过任何类型的成员工作 - 无论是对象属性还是关联数组元素(for不会被捕获)。它通常最适合可读性。
which should be used when we loop inside another loop?
当我们在另一个循环中循环时应该使用哪个?
Both are fine; in your demo case, foreachis the simplest way to go.
两者都很好;在您的演示案例中,foreach是最简单的方法。
回答by Brendan Long
which one is better for performance?
哪个性能更好?
Who cares? It won't be significant. Ever. If these sorts of tiny optimizations mattered, you wouldn't be using PHP.
谁在乎?不会很有意义。曾经。如果这些微小的优化很重要,那么您就不会使用 PHP。
what's the criteria to select a loop?
选择循环的标准是什么?
Pick the one that's easiest to read and least likely to cause mistakes in the future. When you're looping through integers, forloops are great. When you're looping through a collection like an array, foreachis great, when you just need to loop until you're "done", whileis great.
选择最容易阅读且将来最不可能导致错误的内容。当您遍历整数时,for循环很棒。当您像数组一样循环遍历集合时,foreach这很棒,当您只需要循环直到“完成”时,while这很棒。
This may depend on stylistic rules too (for example, in Python you almost always want to use a foreach loop because that's "the way it's done in Python"). I'm not sure what the standard is in PHP though.
这也可能取决于文体规则(例如,在 Python 中,您几乎总是想使用 foreach 循环,因为这是“在 Python 中完成的方式”)。我不确定 PHP 中的标准是什么。
which should be used when we loop inside another loop?
当我们在另一个循环中循环时应该使用哪个?
Whichever loop type makes the most sense (see the answer above).
无论哪种循环类型最有意义(请参阅上面的答案)。
In your code, the forloop seems pretty natural to me, since you have a defined start and stop index.
在您的代码中,for循环对我来说似乎很自然,因为您有一个定义的开始和停止索引。
回答by Jason
Check http://www.phpbench.com/for a good reference on some PHP benchmarks.
检查http://www.phpbench.com/以获得一些 PHP 基准测试的良好参考。
The for loop is usually pretty fast. Don't include your count($rows) or count($all) in the for itself, do it outside like so:
for 循环通常很快。不要在 for 本身中包含您的 count($rows) 或 count($all),在外面这样做:
$count_all = count($all);
for($i=0;$i<$count_all;$i++)
{
// Code here
}
Placing the count($all) in the for loop makes it calculate this statement for each loop. Calculating the value first, and then using the calculation in the loop makes it only run once.
将 count($all) 放在 for 循环中使其为每个循环计算此语句。首先计算值,然后在循环中使用计算使其只运行一次。
回答by JvdBerg
- For performance it does not matter if you choose a
foror awhileloop, the number of iterations determine execution time. - If you know the number of iterations at forehand, choose a
forloop. If you want to run and stop on a condition, use awhileloop
- 对于性能而言,选择 a
for还是while循环并不重要,迭代次数决定了执行时间。 - 如果您知道正手的迭代次数,请选择一个
for循环。如果要在条件下运行和停止,请使用while循环
回答by yohannes
- for loop is more appropriate when you know in advance how many iterations to perform
- While loop is used in the opposite case(when you don't know how many iterations are needed)
- For-Each loop is best when you have to iterate over collections.
- 当您提前知道要执行多少次迭代时,for 循环更合适
- While 循环用于相反的情况(当您不知道需要多少次迭代时)
- 当您必须迭代集合时,For-Each 循环是最好的。
To the best of my knowledge, there is little to no performance difference between while loop and for loop i don't know about the for-each loop
据我所知,while 循环和 for 循环之间几乎没有性能差异我不知道 for-each 循环
回答by Absolute?ER?
Performance:Easy enough to test. If you're doing something like machine learning or big data you should really look at something that's compiledor assembledand not interpretedthough; if the cycles reallymatter. Here are some benchmarks between the various programming languages.It looks like do-whileloop is the winner on my systems using PHPwith these examples.
性能:易于测试。如果你正在做机器学习或大数据之类的事情,你应该真正关注一些编译或组装而不是解释的东西;如果周期真的很重要。以下是各种编程语言之间的一些基准。看起来do-while循环是使用PHP这些示例的系统的赢家。
$my_var = "some random phrase";
function fortify($my_var){
for($x=0;isset($my_var[$x]);$x++){
echo $my_var[$x]." ";
}
}
function whilst($my_var){
$x=0;
while(isset($my_var[$x])){
echo $my_var[$x]." ";
$x++;
}
}
function dowhilst($my_var){
$x=0;
do {
echo $my_var[$x]." ";
$x++;
} while(isset($my_var[$x]));
}
function forstream(){
for($x=0;$x<1000001;$x++){
//simple reassignment
$v=$x;
}
return "For Count to $v completed";
}
function whilestream(){
$x=0;
while($x<1000001){
$v=$x;
$x++;
}
return "While Count to 1000000 completed";
}
function dowhilestream(){
$x=0;
do {
$v=$x;
$x++;
} while ($x<1000001);
return "Do while Count to 1000000 completed";
}
function dowhilestream2(){
$x=0;
do {
$v=$x;
$x++;
} while ($x!=1000001);
return "Do while Count to 1000000 completed";
}
$array = array(
//for the first 3, we're adding a space after every character.
'fortify'=>$my_var,
'whilst'=>$my_var,
'dowhilst'=>$my_var,
//for these we're simply counting to 1,000,000 from 0
//assigning the value of x to v
'forstream'=>'',
'whilestream'=>'',
'dowhilestream'=>'',
//notice how on this one the != operator is slower than
//the < operator
'dowhilestream2'=>''
);
function results($array){
foreach($array as $function=>$params){
if(empty($params)){
$time= microtime();
$results = call_user_func($function);
} elseif(!is_array($params)){
$time= microtime();
$results = call_user_func($function,$params);
} else {
$time= microtime();
$results = call_user_func_array($function,$params);
}
$total = number_format(microtime() - $time,10);
echo "<fieldset><legend>Result of <em>$function</em></legend>".PHP_EOL;
if(!empty($results)){
echo "<pre><code>".PHP_EOL;
var_dump($results);
echo PHP_EOL."</code></pre>".PHP_EOL;
}
echo "<p>Execution Time: $total</p></fieldset>".PHP_EOL;
}
}
results($array);
Criteria:while, for, and foreachare the major control structures most people use in PHP. do-whileis faster than whilein my tests, but largely underused in most PHP coding examples on the web.
标准:while、for和foreach是大多数人在 PHP 中使用的主要控制结构。do-while比while我的测试更快,但在网络上的大多数 PHP 编码示例中基本上没有得到充分利用。
foris count controlled, so it iterates a specific number of times; though it is slower in my own results than using a whilefor the same thing.
for受计数控制,因此它会迭代特定次数;尽管在我自己的结果中它比while对同一件事使用 a 慢。
whileis good when something might start out as false, so it can prevent something from ever running and wasting resources.
while当某些东西可能以 开始时很好false,因此它可以防止某些东西运行和浪费资源。
do-whileat least once, and then until the condition returns false. It's a little faster than a whileloop in my results, but it's going to run at least once.
do-while至少一次,然后直到条件返回false。它比while我的结果中的循环快一点,但它至少会运行一次。
foreachis good for iterating through an arrayor object. Even though you can loop through a string with a forstatement using array syntax you can't use foreach to do it though in PHP.
foreach适合遍历arrayor object。即使您可以for使用数组语法使用语句循环遍历字符串,但在 PHP 中不能使用 foreach 来执行此操作。
Control Structure Nesting:It really depends on what you're doing to determine while control structure to use when nesting. In some cases like Object Oriented Programming you'll actually want to call functions that contain your control structures (individually) rather than using massive programs in procedural style that contain many nested controls. This can make it easier to read, debug, and instantiate.
控制结构嵌套:这实际上取决于您在做什么来确定嵌套时要使用的控制结构。在某些情况下,例如面向对象编程,您实际上希望调用包含您的控制结构(单独)的函数,而不是使用包含许多嵌套控件的程序风格的大量程序。这可以使阅读、调试和实例化更容易。

