If else 运营商与捷径

If else operator with short way

我有 if else 运算符和语句

$row["column"] = ($example == "H") ? "first" : "second";

我需要为此添加 else if 条件。需要编写类似下面的代码,但带有 ?:。寻找更短的代码方式,可能吗?

if($example == "H")
{
  $example = "first";
}
else if($example == "K")
{
  $example = "smth different";
}
else if($example == "X")
{
  $example =" third one";
}
else
{
  $example = "go away";
{

你可以嵌套它们:

$row["column"] = ($example == "H") ? "first" : $row["column"] = ($example == "K") ? "smth different" : ...;

另外我建议使用 switch 而不是这个

链接三元运算符不是一个好主意。更短的代码并不总是意味着它更具可读性!如果你在另一个内部使用多个三元运算符,它很快就会变得不可读。

相反,使用 switch 检查每个案例。

switch ($example) {
    case "H":
        $example = "first";
        break;
    case "K":
        $example = "smth different";
        break;
    case "X":
        $example =" third one";
        break;
    default:
        $example = "go away";
}

使用 associative array:

$map = [
  'H' => 'first',
  'K' => 'smth different',
  'X' => 'third one',
];

$val = 'go away';
if (isset($map[$example])) {
  $val = $map[$example];
}

echo $val;

或使用switch语句:

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;

您可以使用 switch 语句代替 if/else,示例:

switch ($example)
{
    case 'A':
        $example = 'first';
        break;
    case 'B':
        $example = 'second';
        break;
    default:
        $example = 'default';
}