我有以下代码适用于两个选项,
<?php echo ($color) ? '#111' : '#222';?>
Run Code Online (Sandbox Code Playgroud)
但是当我尝试添加更多内容时,我收到一条错误消息,指出未执行的“:”或“;”。
<?php echo ($color) ? '#111' : '#222' : '#333' : '#444';?>
Run Code Online (Sandbox Code Playgroud)
我如何调整它以适应两个以上的选项?
您可以链接三元 if/else:
condidition ? ifTrue : (condition2 ? if2True : (condition3 : ifTrue : ifFalse))
Run Code Online (Sandbox Code Playgroud)
但这会变得很难快速阅读。使用 elseif 更容易:
if(condidition){
ifTrue
} elseif(condidition2){
if2True
}(condidition3){
if3True
}
Run Code Online (Sandbox Code Playgroud)
或一个开关:
switch($level){
case "info": return 'blue';
case "warning": return 'orange';
case "error" :return 'red';
}
Run Code Online (Sandbox Code Playgroud)
或者与 php8 匹配:
$color = match ($level) {
"info" => 'blue',
"warning" =>'orange',
"error" => 'red',
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
54 次 |
| 最近记录: |