循环 – PHP 基础知识
每当您希望代码在行中一遍又一遍地运行时,就可以使用循环。我们使用循环而不是多次添加几乎相同的代码。
循环语句:
只要条件为真,循环就会继续 – while
循环继续一次代码并重复循环,直到指定的条件为真 – do…while
循环持续一定时间 – for
循环为数组中的每个元素继续执行代码块 – foreach
while 循环:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 10;
while($x <= 20) {
echo "The number is: $x <br>";
$x++;
}
?>
</body>
</html>
输出 :
do…while 循环:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 10);
?>
</body>
</html>
输出 :
for 循环:
<!DOCTYPE html>
<html>
<body>
<?php
for ($a = 0; $a <= 10; $a++) {
echo "code-projects.org <br>";
}
?>
</body>
</html>
输出 :
foreach 循环:
<!DOCTYPE html>
<html>
<body>
<?php
$lang = array("php", "python", "c++", "c#");
foreach ($lang as $value) {
echo "$value <br>";
}
?>
</body>
</html>
输出 :