Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using more than 2 options in PHP echo

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading