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';
}
?>
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:
$vocations = array(
1 => "Sorcerer",
2 => "Druid",
3 => "Paladin",
...
);
echo $vocations[$result->vocation];
A ternary for this application would end up looking like this:
echo($result->group_id == 1 ? "Player" : ($result->group_id == 2 ? "Gamemaster" : ($result->group_id == 3 ? "God" : "unknown")));
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:
$value = ($condition) ? 'Truthy Value' : 'Falsey Value';
or
echo ($some_condition) ? 'The condition is true!' : 'The condition is false.';
A ternary is really just a convenient / shorter way to write a simple if else
statement. The above sample ternary is the same as:
if ($some_condition) {
echo 'The condition is true!';
} else {
echo 'The condition is false!';
}
However, a ternary for a complex logic quickly becomes unreadable, and is no longer worth the brevity.
echo($result->group_id == 1 ? "Player" : ($result->group_id == 2 ? "Gamemaster" : ($result->group_id == 3 ? "God" : "unknown")));
Even with some attentive formatting to spread it over multiple lines, it's not very clear:
echo($result->group_id == 1
? "Player"
: ($result->group_id == 2
? "Gamemaster"
: ($result->group_id == 3
? "God"
: "unknown")));