PHP If...Else

if / elseif / else, ternaries, alternative syntax, and common falsy pitfalls.

Beginner
Key Points`if` tests truthiness; 0, "", "0", null and [] are all falsy in PHP.

基本结构

PHP
<?php
$score = 85;

if ($score >= 90) {
    echo "优秀\n";
} elseif ($score >= 80) {
    echo "良好\n";
} elseif ($score >= 60) {
    echo "及格\n";
} else {
    echo "不及格\n";
}
Output
良好

Both elseif and else if work. Note that elseif is a single word — else if breaks under the alternative syntax.

真假值

PHP coerces to boolean loosely; all of these are false:

ValueboolNote
falsefalse字面量
0false整数零
0.0false浮点零
""false空字符串
"0"falsethe only non-empty falsy string
[]false空数组
nullfalse空值
"0.0" / " "true非空且不是 "0"
The falsiness of "0" trips up everyone. When checking whether a field was filled, use isset() or !== ''.

三元与简写

PHP
<?php
$score = 85;

echo $score >= 60 ? "通过" : "未通过", "\n";

// 嵌套三元必须加括号(PHP 8 起不加会报错)
$grade = $score >= 90 ? "A" : ($score >= 80 ? "B" : "C");
echo $grade, "\n";

// Elvis:左边为假取右边
$nick = "";
echo ($nick ?: "游客"), "\n";

// 空合并:左边为 null / 未定义取右边
echo ($undefined ?? "兜底"), "\n";
Output
通过
B
游客
兜底

替代语法

When mixing HTML into templates, if: ... endif; reads far cleaner than braces. Laravel Blade and WordPress themes use it.

PHP
<?php $isLogin = true; $user = "Tom"; ?>

<?php if ($isLogin): ?>
    <p>欢迎回来,<?= $user ?></p>
<?php else: ?>
    <p>请先登录</p>
<?php endif; ?>
Output
<p>欢迎回来,Tom</p>

<?= $x ?> is shorthand for <?php echo $x; ?>, always available since 5.4. Escape user data with htmlspecialchars().

常见写法

  • Early return —— if (!$ok) return; first, avoiding deep nesting
  • **Never write if ($x == true)** —— just if ($x)
  • Constant on the left —— if (1 === $x) guards against a stray =
  • **empty() vs isset()** —— empty() is true for "0" too, use with care

Friends & Partners