If 语句
If 语句用于在条件评估为 true 时执行代码块。当条件判断为 false 时,程序将跳过 if 代码块。
语法
if(condition) {
statements;
}
流程图:

在下面的示例中,if 代码块被创建,仅当变量 i 能被 3 整除时才执行。
<?php
$i = 15;
if ($i % 3 == 0) {
echo "$i 能被 3 整除.";
}
?>
上述代码的输出将是:
15 能被 3 整除.
If-else 语句
else 语句始终与if 语句一起使用。它用于在 if 条件给出错误结果时执行代码块。
语法
if(condition) {
statements;
} else {
statements;
}
流程图:

在示例中下面,else 语句用于在变量 i 不能被 3 整除时打印一条消息。
<?php
$i = 16;
if ($i % 3 == 0){
echo "$i 能被 3 整除.";
} else {
echo "$i 不能被 3 整除.";
}
?>
上述代码的输出将是:
16 不能被 3 整除.
elseif语句
为了添加更多条件,使用elseif语句。程序首先检查if条件。当发现错误时,它会检查 elseif 条件。如果发现所有 elseif 条件均为 false,则执行 else 代码块。
语法
if(condition) {
statements;
} elseif(condition) {
statements;
}
...
...
...
} else {
statements;
}
流程图表:

在下面的示例中,elseif语句用于在if语句和else语句之间添加更多条件。
<?php
$i = 16;
if ($i > 25){
echo $i." 大于25.\n";
} elseif ($i <=25 && $i >=10) {
echo $i." 介于 10 到 25 之间.\n";
} else {
echo $i." 小于 10.\n";
}
?>
上述代码的输出将是:
16 介于 10 到 25 之间.