How do I write a PHP ternary operator with the elseif portion?
I see basic examples with the if
and else
portions of the PHP ternary operator like this:
echo (true) ? "yes" : "no"; //prints yes
echo (false) ? "yes" : "no"; //prints no
How do I get the "elseif" portion like this into the ternary operator?
<?php
if($result->vocation == 1){
echo "Sorcerer";
}else if($result->vocation == 2){
echo 'Druid';
}else if($result->vocation == 3){
echo 'Paladin';
}else if($result->vocation == 4){
echo 'Knight';
}else if($result->vocation == 5){
echo 'Master Sorcerer';
}else if($result->vocation == 6){
echo 'Elder Druid';
}else if($result->vocation == 7){
echo 'Royal Paladin';
}else{
echo 'Elite Knight';
}
?>
I'd rather than ternary if-statements go with a switch-case. For example:
You could also do:
Instead of:
It’s kind of ugly. You should stick with normal
if
statements.In addition to all the other answers, you could use
switch
. But it does seem a bit long.To be honest, a ternary operator would only make this worse, what i would suggest if making it simpler is what you are aiming at is:
and then a similar one for your vocations
With a ternary operator, you would end up with
Which as you can tell, only gets more complicated the more you add to it
A Ternary is not a good solution for what you want. It will not be readable in your code, and there are much better solutions available.
Why not use an array lookup "map" or "dictionary", like so:
A ternary for this application would end up looking like this:
Why is this bad? Because - as a single long line, you would get no valid debugging information if something were to go wrong here, the length makes it difficult to read, plus the nesting of the multiple ternaries just feels odd.
A Standard Ternary is simple, easy to read, and would look like this:
or
A ternary is really just a convenient / shorter way to write a simple
if else
statement. The above sample ternary is the same as:However, a ternary for a complex logic quickly becomes unreadable, and is no longer worth the brevity.
Even with some attentive formatting to spread it over multiple lines, it's not very clear: