I have if else operators with statement
$row["column"] = ($example == "H") ? "first" : "second";
I need to add else if
condition to this. Need to write something like code bellow but with ?
and :
. Looking for shorter code way, is it possible?
if($example == "H")
{
$example = "first";
}
else if($example == "K")
{
$example = "smth different";
}
else if($example == "X")
{
$example =" third one";
}
else
{
$example = "go away";
{
Chaining ternary operators isn't a good idea. Shorter code doesn't always mean its more readable! If you use multiple ternary operators inside one another, it very quickly becomes unreadable.
Instead, use a switch
that checks for each case.
switch ($example) {
case "H":
$example = "first";
break;
case "K":
$example = "smth different";
break;
case "X":
$example =" third one";
break;
default:
$example = "go away";
}
you can just nest them:
$row["column"] = ($example == "H") ? "first" : $row["column"] = ($example == "K") ? "smth different" : ...;
also I would recommend using switch not this
Use an associative array:
$map = [
'H' => 'first',
'K' => 'smth different',
'X' => 'third one',
];
$val = 'go away';
if (isset($map[$example])) {
$val = $map[$example];
}
echo $val;
Or use a switch
statement:
switch ($example) {
case 'H':
$val = 'first';
break;
case 'K':
$val = 'smth different';
break;
case 'X':
$val = 'third one';
break;
default:
$val = 'go away';
break;
}
echo $val;
You can use a switch statement instead of an if/else, example:
switch ($example)
{
case 'A':
$example = 'first';
break;
case 'B':
$example = 'second';
break;
default:
$example = 'default';
}