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
}