循环之间的区别 [英] The difference between loops
问题描述
这是关于PHP的,但毫无疑问,许多相同的注释将适用于其他语言.
It's about PHP but I've no doubt many of the same comments will apply to other languages.
简单地说,PHP的不同循环类型有何不同?一个比另一个更快/更好吗?还是我应该简单地放在最易读的循环中?
Simply put, what are the differences in the different types of loop for PHP? Is one faster/better than the others or should I simply put in the most readable loop?
for ($i = 0; $i < 10; $i++)
{
# code...
}
foreach ($array as $index => $value)
{
# code...
}
do
{
# code...
}
while ($flag == false);
推荐答案
For循环和While循环是进入条件循环.他们首先评估条件,因此即使条件不满足,与循环关联的语句块也不会运行一次
For loop and While loops are entry condition loops. They evaluate condition first, so the statement block associated with the loop won't run even once if the condition fails to meet
此for循环块中的语句将运行10次,$ i的值将为0到9;
The statements inside this for loop block will run 10 times, the value of $i will be 0 to 9;
for ($i = 0; $i < 10; $i++)
{
# code...
}
与while循环相同的事情:
Same thing done with while loop:
$i = 0;
while ($i < 10)
{
# code...
$i++
}
Do-while循环是退出条件循环.确保执行一次,然后在重复执行该块之前先评估条件
Do-while loop is exit-condition loop. It's guaranteed to execute once, then it will evaluate condition before repeating the block
do
{
# code...
}
while ($flag == false);
foreach用于从头到尾访问数组元素.在foreach循环开始时,将数组的内部指针设置为数组的第一个元素,在下一步中,将其设置为数组的第二个元素,依此类推,直到数组结束.在循环块中,当前数组项的值可用作$ value,而当前项的键可用作$ index.
foreach is used to access array elements from start to end. At the beginning of foreach loop, the internal pointer of the array is set to the first element of the array, in next step it is set to the 2nd element of the array and so on till the array ends. In the loop block The value of current array item is available as $value and the key of current item is available as $index.
foreach ($array as $index => $value)
{
# code...
}
您可以使用while循环执行相同的操作,例如
You could do the same thing with while loop, like this
while (current($array))
{
$index = key($array); // to get key of the current element
$value = $array[$index]; // to get value of current element
# code ...
next($array); // advance the internal array pointer of $array
}
最后: PHP手册是您的朋友:)
这篇关于循环之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!