Home > Software engineering >  Using more than 2 options in PHP echo
Using more than 2 options in PHP echo

Time:03-03

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?

CodePudding user response:

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',
};

CodePudding user response:

"?" - it's just a shorthand for php if/else control structure. So you can move in the way like this:

if ($color == 1) {
   echo '#111';
} elseif ($color == 2) {
   echo '#222'; 
}
...
etc

CodePudding user response:

The line you posted is basically a shortened if statement. It can only have 2 options (is $color true or false). You can use switch instead - switch

  •  Tags:  
  • php
  • Related