For 循环和 While 循环是入口条件循环。他们首先评估条件,因此即使条件不满足,与循环关联的语句块也不会运行一次
这个for循环块里面的语句会运行10次,$i的值是0到9;
for ($i = 0; $i < 10; $i++)
{
# code...
}
用while循环做同样的事情:
$i = 0;
while ($i < 10)
{
# code...
$i++
}
Do-while 循环是退出条件循环。它保证执行一次,然后它会在重复块之前评估条件
do
{
# code...
}
while ($flag == false);
foreach 用于从头到尾访问数组元素。在 foreach 循环开始时,将数组的内部指针设置为数组的第一个元素,下一步将其设置为数组的第二个元素,依此类推,直到数组结束。在循环块中,当前数组项的值以 $value 的形式提供,当前项的键以 $index 的形式提供。
foreach ($array as $index => $value)
{
# code...
}
你可以用while循环做同样的事情,像这样
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
}
最后:The PHP Manual 是你的朋友 :)