How to write a PHP ternary operator -
how write php ternary operator elseif portion?
i see basic examples if
, else
portions of php ternary operator this:
echo (true) ? "yes" : "no"; //prints yes echo (false) ? "yes" : "no"; //prints no
how "elseif" portion 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 not solution want. not readable in code, , there better solutions available.
why not use array lookup "map" or "dictionary", so:
$vocations = array( 1 => "sorcerer", 2 => "druid", 3 => "paladin", ... ); echo $vocations[$result->vocation];
a ternary application end looking this:
echo($result->group_id == 1 ? "player" : ($result->group_id == 2 ? "gamemaster" : ($result->group_id == 3 ? "god" : "unknown")));
why bad? because - single long line, no valid debugging information if go wrong here, length makes difficult read, plus nesting of multiple ternaries feels odd.
a standard ternary simple, easy read, , this:
$value = ($condition) ? 'truthy value' : 'falsey value';
or
echo ($some_condition) ? 'the condition true!' : 'the condition false.';
a ternary convenient / shorter way write simple if else
statement. above sample ternary same as:
if ($some_condition) { echo 'the condition true!'; } else { echo 'the condition false!'; }
however, ternary complex logic becomes unreadable, , no longer worth brevity.
echo($result->group_id == 1 ? "player" : ($result->group_id == 2 ? "gamemaster" : ($result->group_id == 3 ? "god" : "unknown")));
even attentive formatting spread on multiple lines, it's not clear:
echo($result->group_id == 1 ? "player" : ($result->group_id == 2 ? "gamemaster" : ($result->group_id == 3 ? "god" : "unknown")));
Comments
Post a Comment