I have the following code which works for two options,
<?php echo ($color) ? '#111' : '#222';?>
But when I try to add more, I get an error message saying unexected ":" or ";".
<?php echo ($color) ? '#111' : '#222' : '#333' : '#444';?>
How I can adapt this to work with more than two options?
>Solution :
You can chain the ternary if/else:
condidition ? ifTrue : (condition2 ? if2True : (condition3 : ifTrue : ifFalse))
But that’ll become difficult to read very fast. It’s a lot easier to use elseif:
if(condidition){
ifTrue
} elseif(condidition2){
if2True
}(condidition3){
if3True
}
or a switch:
switch($level){
case "info": return 'blue';
case "warning": return 'orange';
case "error" :return 'red';
}
or with php8 a match:
$color = match ($level) {
"info" => 'blue',
"warning" =>'orange',
"error" => 'red',
};