条件语句是PHP编程中的基本构建块,用于基于不同条件执行不同的代码路径。If...Else语句是最常用的条件控制结构,它允许程序根据条件的真假值做出决策。
在编写PHP代码时,经常需要根据不同的条件执行不同的操作。PHP提供了以下几种条件语句来实现这种逻辑:
if 语句是最基本的条件语句,只有当指定条件为 true 时才会执行相应的代码块。
if (condition) {
// 当条件为 true 时执行的代码
}
<?php
// 简单的 if 语句示例
$age = 18;
if ($age >= 18) {
echo "您已成年,可以进入网站。";
}
// 检查变量是否存在
$username = "张三";
if ($username) {
echo "欢迎," . $username;
}
// 使用比较运算符
$score = 85;
if ($score >= 60) {
echo "恭喜!您通过了考试。";
}
// 使用逻辑运算符
$isLoggedIn = true;
$hasPermission = true;
if ($isLoggedIn && $hasPermission) {
echo "您有权限访问此页面。";
}
// 检查数组是否为空
$fruits = array("苹果", "香蕉", "橙子");
if (count($fruits) > 0) {
echo "水果数组中有 " . count($fruits) . " 个元素。";
}
?>
提示: 在PHP中,以下值在条件判断中会被认为是 false:布尔值 false、整数 0、浮点数 0.0、空字符串 ""、字符串 "0"、空数组、NULL。
if...else 语句在条件为 true 时执行一个代码块,在条件为 false 时执行另一个代码块。
if (condition) {
// 当条件为 true 时执行的代码
} else {
// 当条件为 false 时执行的代码
}
<?php
// 基本的 if...else 语句
$time = 15;
if ($time < 18) {
echo "Good day";
} else {
echo "Good evening";
}
// 用户权限检查
$userRole = "guest";
if ($userRole === "admin") {
echo "欢迎管理员!";
} else {
echo "欢迎访客!";
}
// 数字奇偶性判断
$number = 7;
if ($number % 2 === 0) {
echo $number . " 是偶数";
} else {
echo $number . " 是奇数";
}
// 表单验证示例
$email = "user@example.com";
if (strpos($email, "@") !== false) {
echo "邮箱格式正确";
} else {
echo "请输入有效的邮箱地址";
}
// 文件存在性检查
$filename = "config.php";
if (file_exists($filename)) {
echo "配置文件存在";
} else {
echo "配置文件不存在";
}
?>
当需要检查多个条件时,可以使用 if...else if...else 语句。它会按顺序检查每个条件,执行第一个为 true 的条件对应的代码块。
if (condition1) {
// 当条件1为 true 时执行的代码
} else if (condition2) {
// 当条件2为 true 时执行的代码
} else if (condition3) {
// 当条件3为 true 时执行的代码
} else {
// 当所有条件都不为 true 时执行的代码
}
<?php
// 根据时间问候
$hour = date("H");
$greeting = "";
if ($hour < 10) {
$greeting = "Good morning";
} else if ($hour >= 10 && $hour < 20) {
$greeting = "Good day";
} else {
$greeting = "Good evening";
}
echo $greeting;
// 成绩等级评定
$score = 85;
$grade = "";
if ($score >= 90) {
$grade = "A";
} else if ($score >= 80) {
$grade = "B";
} else if ($score >= 70) {
$grade = "C";
} else if ($score >= 60) {
$grade = "D";
} else {
$grade = "F";
}
echo "您的成绩等级是: " . $grade;
// 用户角色权限管理
$role = "moderator";
$permissions = array();
if ($role === "admin") {
$permissions = array("read", "write", "delete", "manage_users");
} else if ($role === "moderator") {
$permissions = array("read", "write", "delete");
} else if ($role === "user") {
$permissions = array("read", "write");
} else {
$permissions = array("read");
}
echo "您的权限: " . implode(", ", $permissions);
// 月份季节判断
$month = date("n");
$season = "";
if ($month >= 3 && $month <= 5) {
$season = "春季";
} else if ($month >= 6 && $month <= 8) {
$season = "夏季";
} else if ($month >= 9 && $month <= 11) {
$season = "秋季";
} else {
$season = "冬季";
}
echo "当前季节是: " . $season;
?>
注意: 在PHP中,elseif 和 else if 都可以使用,它们是等价的。但为了代码一致性,建议选择一种风格并坚持使用。
可以在 if 或 else 代码块内部再使用 if 语句,这称为嵌套 if 语句。嵌套 if 语句用于处理更复杂的条件逻辑。
<?php
// 嵌套 if 语句示例
$age = 25;
$hasLicense = true;
if ($age >= 18) {
if ($hasLicense) {
echo "您可以驾驶汽车";
} else {
echo "您已成年但没有驾照,不能驾驶";
}
} else {
echo "您未成年,不能驾驶";
}
// 更复杂的嵌套示例
$isMember = true;
$orderAmount = 150;
$discount = 0;
if ($isMember) {
if ($orderAmount > 200) {
$discount = 20; // 会员购买10件以上享受20%折扣
} else if ($orderAmount > 100) {
$discount = 10; // 会员享受10%折扣
} else {
$discount = 5; // 会员基础折扣
}
} else {
if ($orderAmount > 200) {
$discount = 10; // 非会员大额订单折扣
} else {
$discount = 0; // 无折扣
}
}
echo "您的折扣是: " . $discount . "%";
// 登录验证示例
$username = "admin";
$password = "123456";
$isVerified = true;
if ($username === "admin") {
if ($password === "123456") {
if ($isVerified) {
echo "登录成功!";
} else {
echo "请先验证您的账户";
}
} else {
echo "密码错误";
}
} else {
echo "用户名不存在";
}
?>
最佳实践: 虽然嵌套 if 语句很有用,但过度嵌套会使代码难以理解和维护。如果嵌套层级超过3层,建议考虑重构代码。
三元运算符是 if...else 语句的简洁形式,适用于简单的条件判断。
condition ? expression1 : expression2
<?php
// 基本用法
$age = 20;
$canVote = $age >= 18 ? "可以投票" : "不能投票";
echo $canVote;
// 与 if...else 对比
$time = 11;
$greeting = $time < 12 ? "Good morning" : "Good day";
echo $greeting;
// 嵌套三元运算符
$score = 85;
$result = $score >= 90 ? "优秀" :
($score >= 80 ? "良好" :
($score >= 70 ? "中等" :
($score >= 60 ? "及格" : "不及格")));
echo "成绩评定: " . $result;
// 函数返回值的条件赋值
function getFee($isMember) {
return $isMember ? "$2.00" : "$10.00";
}
echo getFee(true); // $2.00
echo getFee(false); // $10.00
echo getFee(null); // $10.00
// 设置默认值
$username = $_POST['username'] ?? '匿名用户';
echo "欢迎, " . $username;
?>
注意: 虽然三元运算符很简洁,但过度使用或嵌套会使代码难以阅读。对于复杂的条件逻辑,建议使用 if...else 语句。
逻辑运算符(&&, ||, !)经常与条件语句结合使用,创建更复杂的条件表达式。
<?php
// 使用 && (AND) 运算符
$age = 25;
$hasLicense = true;
if ($age >= 18 && $hasLicense) {
echo "您可以驾驶";
}
// 使用 || (OR) 运算符
$isWeekend = true;
$isHoliday = false;
if ($isWeekend || $isHoliday) {
echo "今天是休息日";
}
// 使用 ! (NOT) 运算符
$isLoggedIn = false;
if (!$isLoggedIn) {
echo "请先登录";
}
// 组合使用逻辑运算符
$temperature = 25;
$isSunny = true;
$isWeekendDay = true;
if (($temperature > 20 && $isSunny) || $isWeekendDay) {
echo "适合户外活动";
}
// 使用空值合并运算符 (PHP 7+)
$user = [
'name' => '张三',
'preferences' => [
'theme' => 'dark'
]
];
// 安全地访问嵌套属性
if (isset($user['preferences']['theme'])) {
echo "用户主题: " . $user['preferences']['theme'];
}
// 使用可选链操作符 (PHP 8+)
// if ($user?->preferences?->theme) {
// echo "用户主题: " . $user->preferences->theme;
// }
?>
<?php
// 表单验证函数
function validateForm($username, $email, $password) {
$errors = [];
// 用户名验证
if (empty($username)) {
$errors[] = "用户名不能为空";
} else if (strlen($username) < 3) {
$errors[] = "用户名至少需要3个字符";
}
// 邮箱验证
if (empty($email)) {
$errors[] = "邮箱不能为空";
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "请输入有效的邮箱地址";
}
// 密码验证
if (empty($password)) {
$errors[] = "密码不能为空";
} else if (strlen($password) < 6) {
$errors[] = "密码至少需要6个字符";
}
// 返回验证结果
if (empty($errors)) {
return ['success' => true, 'message' => '验证通过'];
} else {
return ['success' => false, 'message' => '验证失败', 'errors' => $errors];
}
}
// 测试表单验证
$result = validateForm("john", "john@example.com", "123456");
print_r($result);
?>
<?php
// 价格计算函数
function calculatePrice($quantity, $isMember, $couponCode) {
$basePrice = 10; // 商品基础价格
$total = $basePrice * $quantity;
$discount = 0;
// 会员折扣
if ($isMember) {
if ($quantity > 10) {
$discount = 20; // 会员购买10件以上享受20%折扣
} else {
$discount = 10; // 会员享受10%折扣
}
}
// 优惠券折扣
if ($couponCode === "SAVE10") {
$discount = max($discount, 10); // 取最大折扣
} else if ($couponCode === "SAVE20") {
$discount = max($discount, 20);
}
// 应用折扣
if ($discount > 0) {
$total = $total * (1 - $discount / 100);
}
// 运费计算
if ($total < 50) {
$total += 5; // 添加运费
}
return number_format($total, 2);
}
// 测试价格计算
echo "总价格: $" . calculatePrice(5, true, "SAVE10");
?>
<?php
// 重构前:深度嵌套
function processOrder($order) {
if ($order) {
if (!empty($order['items'])) {
if (!empty($order['customer']) && $order['customer']['isActive']) {
// 处理订单
return "订单处理成功";
} else {
return "客户账户未激活";
}
} else {
return "订单中没有商品";
}
} else {
return "无效的订单";
}
}
// 重构后:使用早期返回
function processOrderRefactored($order) {
if (!$order) return "无效的订单";
if (empty($order['items'])) return "订单中没有商品";
if (empty($order['customer']) || !$order['customer']['isActive']) return "客户账户未激活";
// 处理订单
return "订单处理成功";
}
// 测试重构后的函数
echo processOrderRefactored([
'items' => ['item1', 'item2'],
'customer' => ['isActive' => true]
]);
?>