条件语句for if...else switch while

212 阅读2分钟

条件语句

  • 条件语句用于基于不同条件执行不同的动作
  • if 语句 - 如果指定条件为真,则执行代码
  • if...else 语句 - 如果条件为 true,则执行代码;如果条件为 false,则执行另一端代码
  • if...elseif....else 语句 - 根据两个以上的条件执行不同的代码块
  • switch 语句 - 选择多个代码块之一来执行

if语句

  • if 语句用于在指定条件为 true 时执行代码。
if (条件) {
  当条件为 true 时执行的代码;
}

if...else 语句

  • if....else 语句在条件为 true 时执行代码,在条件为 false 时执行另一段代码
if (条件) {
  条件为 true 时执行的代码;
} else {
  条件为 false 时执行的代码;
}

if...elseif....else 语句

  • if....elseif...else 语句来根据两个以上的条件执行不同的代码
if (条件) {
  条件为 true 时执行的代码;
} elseif (condition) {
  条件为 true 时执行的代码;
} else {
  条件为 false 时执行的代码;
}

switch语句

  • switch 语句用于基于不同条件执行不同动作
  • 如果您希望有选择地执行若干代码块之一,请使用 Switch 语句
  • 使用 Switch 语句可以避免冗长的 if..elseif..else 代码块
switch (expression)
{
case label1:
  expression = label1 时执行的代码 ;
  break;  
case label2:
  expression = label2 时执行的代码 ;
  break;
default:
  表达式的值不等于 label1 及 label2 时执行的代码;
}
  • 工作原理:
1. 对表达式(通常是变量)进行一次计算
2. 把表达式的值与结构中 case 的值进行比较
3. 如果存在匹配,则执行与 case 关联的代码
4. 代码执行后,break 语句阻止代码跳入下一个 case 中继续执行
5. 如果没有 case 为真,则使用 default 语句

while 循环

  • while 循环在指定条件为 true 时执行代码块
  • 只要指定的条件为真,while 循环就会执行代码块
while (条件为真) {
  要执行的代码;
}

do...while 循环

  • do...while 循环首先会执行一次代码块,然后检查条件,如果指定条件为真,则重复循环,一直到条件为假时,停止循环
  • do while 循环只在执行循环内的语句之后才对条件进行测试。这意味着 do while 循环至少会执行一次语句,即使条件测试在第一次就失败了
do {
  要执行的代码;
} while (条件为真);

for 循环

  • for 循环执行代码块指定的次数
for (init counter; test counter; increment counter) {
  code to be executed;
}

init counter:初始化循环计数器的值
test counter:: 评估每个循环迭代。如果值为 TRUE,继续循环。如果它的值为 FALSE,循环结束。
increment counter:增加循环计数器的值

例如:
for ($x=0; $x<=10; $x++) {
  echo "数字是:$x ";
} 

foreach 循环--只适用 数组

  • foreach 循环只适用于数组,并用于遍历数组中的每个键/值对
foreach ($array as $value) {
  code to be executed;
}
或者
foreach ($array as $index=>$value) {
  code to be executed;
}