0

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?

2
  • 1
    Just to state the obvious here, ? : is basically if(true) { } else { }. You can only ever have two options if all you evaluate is true vs. false, regardless of the syntax or construct you may use. Based on what evaluation do you reckon your other options would ever be chosen? Commented Mar 3, 2022 at 10:48
  • Yeah I was having a blonde moment lol Commented Mar 3, 2022 at 11:53

3 Answers 3

7

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',
};
Sign up to request clarification or add additional context in comments.

7 Comments

I think this if - else chain would also become hard to read, and switch is a better alternative in this case
@tola I agree, but that only goes if there are multiple possibilities for one variable. If different checks have to be made, then an elseif is the way to go :)
you're right. I just figured, based on the question, it is a single variable in this case
All great answers, thank you, I'm really rusty haven't been hand coding for about 4-5 years, so simple things need my memory jogging.
@GibsonFX that is not how this site works :) The best answer gets the Checkbox. The reason is so the next person cant find an answer quicker. If you think an answer is good you can upvote (you can also do both). You should read it as if you dont know the author
|
1

"?" - 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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.