PHP 条件语句
最后修改于 2025 年 3 月 11 日
在本文中,我们将探讨 PHP 条件语句,它们是用于在代码中做出决策的控制结构。条件语句允许您根据某些条件为真或假来执行不同的代码块。
PHP 条件语句的主要特征
if
:如果条件为真,则执行代码块。else
:如果if
条件为假,则执行代码块。elseif
:如果之前的if
或elseif
条件为假,则检查其他条件。switch
:根据变量的值执行多个代码块中的一个。三元运算符
:用于简单if-else
条件语句的简写形式。
条件语句对于控制您的 PHP 程序的流程至关重要。
条件语句的基本用法
以下示例演示了 PHP 中 if
语句的基本用法。
main.php
<?php declare(strict_types=1); $age = 20; if ($age >= 18) { echo "You are an adult.\n"; }
在此程序中,if
语句检查 $age
变量是否大于或等于 18。如果为真,则打印“你是一个成年人”。
$ php main.php You are an adult.
if-else 语句
以下示例演示了 if-else
语句。
main.php
<?php declare(strict_types=1); $age = 15; if ($age >= 18) { echo "You are an adult.\n"; } else { echo "You are a minor.\n"; }
在此程序中,如果 if
条件为假,则执行 else
块。
$ php main.php You are a minor.
elseif 语句
以下示例演示了 elseif
语句。
main.php
<?php declare(strict_types=1); $age = 25; if ($age < 18) { echo "You are a minor.\n"; } elseif ($age < 30) { echo "You are a young adult.\n"; } else { echo "You are an adult.\n"; }
在此程序中,如果第一个 if
条件为假并且 elseif
条件为真,则执行 elseif
块。
$ php main.php You are a young adult.
三元运算符
以下示例演示了三元运算符。
main.php
<?php declare(strict_types=1); $age = 20; $message = ($age >= 18) ? "You are an adult.\n" : "You are a minor.\n"; echo $message;
在此程序中,三元运算符用作 if-else
语句的简写形式。
$ php main.php You are an adult.
switch 语句
以下示例演示了 switch
语句。
main.php
<?php declare(strict_types=1); $day = "Monday"; switch ($day) { case "Monday": echo "Today is Monday.\n"; break; case "Tuesday": echo "Today is Tuesday.\n"; break; default: echo "Today is not Monday or Tuesday.\n"; }
在此程序中,switch
语句检查 $day
的值并执行相应的代码块。
$ php main.php Today is Monday.
嵌套的 if 语句
以下示例演示了嵌套的 if
语句。
main.php
<?php declare(strict_types=1); $age = 25; $isStudent = true; if ($age >= 18) { if ($isStudent) { echo "You are an adult student.\n"; } else { echo "You are an adult.\n"; } } else { echo "You are a minor.\n"; }
在此程序中,使用嵌套的 if
语句来检查其他条件。
$ php main.php You are an adult student.
逻辑运算符
以下示例演示了在条件语句中使用逻辑运算符。
main.php
<?php declare(strict_types=1); $age = 25; $isStudent = true; if ($age >= 18 && $isStudent) { echo "You are an adult student.\n"; } else { echo "You are not an adult student.\n"; }
在此程序中,使用 &&
(逻辑 AND) 运算符来组合多个条件。
$ php main.php You are an adult student.
空值合并运算符
以下示例演示了空值合并运算符。
main.php
<?php declare(strict_types=1); $name = null; $username = $name ?? "Guest"; echo "Welcome, $username!\n";
在此程序中,使用空值合并运算符 (??
) 在变量为空时分配默认值。
$ php main.php Welcome, Guest!
组合条件
以下示例演示了组合多个条件。
main.php
<?php declare(strict_types=1); $age = 25; $isStudent = false; $hasJob = true; if (($age >= 18 && $hasJob) || $isStudent) { echo "You are eligible for the program.\n"; } else { echo "You are not eligible for the program.\n"; }
在此程序中,使用逻辑运算符组合多个条件。
$ php main.php You are eligible for the program.
来源
在本文中,我们展示了如何在 PHP 中使用条件语句进行控制流。条件语句是您在代码中做出决策的强大工具。
作者
列出 所有 PHP 教程。