在 PHP echo 中使用超过 2 个选项

Gib*_*nFX 0 php

我有以下代码适用于两个选项,

<?php echo ($color) ? '#111' : '#222';?>
Run Code Online (Sandbox Code Playgroud)

但是当我尝试添加更多内容时,我收到一条错误消息,指出未执行的“:”或“;”。

<?php echo ($color) ? '#111' : '#222' : '#333' : '#444';?>
Run Code Online (Sandbox Code Playgroud)

我如何调整它以适应两个以上的选项?

Mar*_*ijn 7

您可以链接三元 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)