在 PHP 中堆叠多个三元运算符

发布于 2024-10-20 21:29:44 字数 316 浏览 4 评论 0原文

这就是我写的:

 $Myprovince = (
($province == 6) ? "city-1" :
($province == 7) ? "city-2" :
($province == 8) ? "city-3" :
($province == 30) ? "city-4" : "out of borders"
);

但是对于每个字段,我都得到了值city-4。我想使用三元运算符而不是 switch/if 因为我想尝试一下并看看它是如何完成的。

这段代码有什么问题?

This is what I wrote :

 $Myprovince = (
($province == 6) ? "city-1" :
($province == 7) ? "city-2" :
($province == 8) ? "city-3" :
($province == 30) ? "city-4" : "out of borders"
);

But for every field I got the value city-4. I want to use ternary operators instead of switch/if because I want to experiment and see how it would be done.

What's the problem with this code?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

乖乖 2024-10-27 21:29:44

其他人已经建议了正确的方法,但如果您确实想使用三元运算符,则需要使用括号:

$province = 7;
 $Myprovince = (
 ($province == 6) ? "city-1" :
  (($province == 7) ? "city-2" :
   (($province == 8) ? "city-3" :
    (($province == 30) ? "city-4" : "out of borders")))
 );

更新链接

Others have already suggested the right way of doing it but if you really want to use ternary operator you need to use parenthesis as:

$province = 7;
 $Myprovince = (
 ($province == 6) ? "city-1" :
  (($province == 7) ? "city-2" :
   (($province == 8) ? "city-3" :
    (($province == 30) ? "city-4" : "out of borders")))
 );

Updated Link

享受孤独 2024-10-27 21:29:44

三元运算符是从左到右计算的。因此,如果您没有正确地对表达式进行分组,您将得到意想不到的结果。

PHP 的建议是 [文档]

建议您避免“堆叠”三元表达式。当在单个语句中使用多个三元运算符时,PHP 的行为并不明显。

您的代码实际上被评估为:

(
    (
        (
            $province == 6 ? "city-1" : $province == 7
        ) ? "city-2" : 
        $province == 8
    ) ? "city-3" : $province == 30
) ? "city-4" : "out of borders";

它应该在哪里

$province == 6 ? "city-1" : (
    $province == 7 ? "city-2" : (
        $province == 8 ? "city-3" : (
           $province == 30 ? "city-4" : "out of borders"
        )
    )
);

该代码可能看起来不错,但有人会阅读它,并且他们需要更多的时间来理解该代码的用途。


你最好像这样:

$map = array( 6 = >'city-1', 
              7 => 'city-2', 
              8 => 'city-3', 
             30 => 'city-4');

$Myprovince = "out of borders";

if(array_key_exists($province, $map)) {
    $Myprovince = $map[$province];
}

或者正如 @Jonah 在他的评论中提到的:

$Myprovince = isset($map[$province]) ? $map[$province] : 'out of borders';

The ternary operator is evaluated from left to right. So if you don't group the expressions properly, you will get an unexpected result.

PHP's advice is [docs]:

It is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious.

Your code actually is evaluated as:

(
    (
        (
            $province == 6 ? "city-1" : $province == 7
        ) ? "city-2" : 
        $province == 8
    ) ? "city-3" : $province == 30
) ? "city-4" : "out of borders";

where it should be

$province == 6 ? "city-1" : (
    $province == 7 ? "city-2" : (
        $province == 8 ? "city-3" : (
           $province == 30 ? "city-4" : "out of borders"
        )
    )
);

This code might look fine but someone will read it and they will need more time than they should to understand what this code is doing.


You would be better off with something like this:

$map = array( 6 = >'city-1', 
              7 => 'city-2', 
              8 => 'city-3', 
             30 => 'city-4');

$Myprovince = "out of borders";

if(array_key_exists($province, $map)) {
    $Myprovince = $map[$province];
}

Or as @Jonah mentioned in his comment:

$Myprovince = isset($map[$province]) ? $map[$province] : 'out of borders';
欢烬 2024-10-27 21:29:44

不要滥用三元运算符来做这类事情。它使得调试几乎不可能进行。为什么不做一些类似的事情

switch($province) {
    case 6: $Myprovince = "city-1"; break;
    case 7: ...
}

或者简单地做一些连锁的 if/then/else

if ($province == 6) {
     $Myprovince = "city-1";
} elseif ($province = ...) {
   ...
}

Don't abuse the ternary operator for that sort of thing. It makes debugging near impossible to follow. Why not do something like

switch($province) {
    case 6: $Myprovince = "city-1"; break;
    case 7: ...
}

or simply some chained if/then/else

if ($province == 6) {
     $Myprovince = "city-1";
} elseif ($province = ...) {
   ...
}
小嗷兮 2024-10-27 21:29:44

有些人建议使用 switch 语句或 if/else 语句。但我会使用数组来代替,以使其更易于维护和阅读:

$provinces = array (
    6 => 'city-1',
    7 => 'city-2',
    8 => 'city-3',
    30 => 'city-4'
);

// then you can call:

$Myprovince = isset($provinces[$province]) ? $provinces[$province] : 'out of borders';

为什么?

代码最终可能会更容易管理。也许有一天您会想从数据库添加这些省到城市的映射......等等。这将很难用一堆 switch/case 语句来维护。

Some people have suggested using a switch statement or an if/else statement. But I would use an array instead, to make it easier to maintain and easier to read:

$provinces = array (
    6 => 'city-1',
    7 => 'city-2',
    8 => 'city-3',
    30 => 'city-4'
);

// then you can call:

$Myprovince = isset($provinces[$province]) ? $provinces[$province] : 'out of borders';

Why?

The code will probably eventually be easier to manage. Maybe you'll want to add those province-to-city mappings from database one day.. etc.. That will be hard to maintain with a bunch of switch/case statements.

彩虹直至黑白 2024-10-27 21:29:44

< PHP 8 中的 code>match 语句

$Myprovince = match ($province) {
    6       => "city-1",
    7       => "city-2",
    8       => "city-3",
    30      => "city-4",
    default => "out of borders",
};

它本质上只是一个不太详细的 switch 语句,非常适合简单赋值。还可以添加多个条件:

$Myprovince = match ($province) {
    4, 5, 6  => "city-1",
    7, 9, 10 => "city-2",
    8        => "city-3",
    30       => "city-4",
    default  => "out of borders",
};

The best and most readable (IMO) solution for this was introduced with the match statement in PHP 8:

$Myprovince = match ($province) {
    6       => "city-1",
    7       => "city-2",
    8       => "city-3",
    30      => "city-4",
    default => "out of borders",
};

It's essentially just a less-verbose switch statement that's ideal for simple assignment. Multiple conditions can be added as well:

$Myprovince = match ($province) {
    4, 5, 6  => "city-1",
    7, 9, 10 => "city-2",
    8        => "city-3",
    30       => "city-4",
    default  => "out of borders",
};
花想c 2024-10-27 21:29:44

尝试使用更多括号:

$Myprovince = (
($province == 6) ? "city-1" :
(($province == 7) ? "city-2" :
(($province == 8) ? "city-3" :
(($province == 30) ? "city-4" : "out of borders"
))));

您的代码在三元运算符优先级方面存在问题。

但我认为你真的应该放弃这个运算符并尝试使用 switch 代替。

Try with some more parenthesis :

$Myprovince = (
($province == 6) ? "city-1" :
(($province == 7) ? "city-2" :
(($province == 8) ? "city-3" :
(($province == 30) ? "city-4" : "out of borders"
))));

Your code has a problem with the ternary operator priority.

But I think you should really drop this operator and try to use a switch instead.

甜尕妞 2024-10-27 21:29:44

我认为在 PHP 中编写嵌套三元运算符的更易读的方法是这样的:

$myprovince =
    $province ==  6 ? "city-1" : (
    $province ==  7 ? "city-2" : (
    $province ==  8 ? "city-3" : (
    $province == 30 ? "city-4" : "out of borders" )));

您需要做的就是计算左括号 (() 的数量并添加相同数量的右括号 ()) 在最后一行的末尾。

另一种选择是使用单行 if/elseif/else,正如已经建议的那样 - 但是,我会像这样直观地格式化它们,以提高可读性:

if      ($province == 6)  $myprovince = "city-1";
elseif  ($province == 7)  $myprovince = "city-2";
elseif  ($province == 8)  $myprovince = "city-3";
elseif  ($province == 30) $myprovince = "city-4";
else                      $myprovince = "out of borders";

I think the more readable way to write nested ternary operators in PHP is like this:

$myprovince =
    $province ==  6 ? "city-1" : (
    $province ==  7 ? "city-2" : (
    $province ==  8 ? "city-3" : (
    $province == 30 ? "city-4" : "out of borders" )));

All you need to do is count the number of opening parenthesis (() and add the same number of closing parenthesis ()) at the end of the last line.

Another option is to use one-line if/elseif/else, as already suggested - however, I would format them visually like this for even more readability:

if      ($province == 6)  $myprovince = "city-1";
elseif  ($province == 7)  $myprovince = "city-2";
elseif  ($province == 8)  $myprovince = "city-3";
elseif  ($province == 30) $myprovince = "city-4";
else                      $myprovince = "out of borders";
兔姬 2024-10-27 21:29:44

我今天也遇到了同样的问题。其他人已经给出了可接受的解决方案。我的只是强调一个班轮如果。我认为更具可读性。

if ($province == 6) $Myprovince = 'city-1';
elseif ($province == 7) $Myprovince = 'city-2';
elseif ($province == 8) $Myprovince = 'city-3';
elseif ($province == 30) $Myprovince = 'city-4';
else $Myprovince = 'out of borders';

I got myself into the same problem today. The others already giving acceptable solutions. Mine just an emphasis to one liner ifs. More readable in my opinion.

if ($province == 6) $Myprovince = 'city-1';
elseif ($province == 7) $Myprovince = 'city-2';
elseif ($province == 8) $Myprovince = 'city-3';
elseif ($province == 30) $Myprovince = 'city-4';
else $Myprovince = 'out of borders';
柠檬心 2024-10-27 21:29:44

请改用开关。三元运算符实际上不应该用于多个条件,因为它们很快就会变得非常难以理解。

switch ($province) {
    case 6:
        $Myprovince = 'city-1';
        break;
    case 7:
        $Myprovince = 'city-2';
        break;
    case 8:
        $Myprovince = 'city-3';
        break;
    case 30:
        $Myprovince = 'city-4';
        break;
    default:
        $Myprovince = 'out of borders';
}

Use switch instead. Ternary operators really shouldn't be used for more than single conditions, as they quickly become very difficult to understand.

switch ($province) {
    case 6:
        $Myprovince = 'city-1';
        break;
    case 7:
        $Myprovince = 'city-2';
        break;
    case 8:
        $Myprovince = 'city-3';
        break;
    case 30:
        $Myprovince = 'city-4';
        break;
    default:
        $Myprovince = 'out of borders';
}
肩上的翅膀 2024-10-27 21:29:44

在这种情况下,我总是建议使用 switch case 语法。正如您所说,它是实验性的,因此这是您需要使用的代码:

$province = 9;
$Myprovince = $province == 6 ? "city-1" : (
    $province == 7 ? "city-2" : (
        $province == 8 ? "city-3" : (
            $province == 9 ? "city-4" : "out of border"
        )
    )
);
echo $Myprovince;

输出将是:

out of border because the $province is = 9

我再次建议使用 switch case。代码下面:

switch ($province) {
    case 6:
        $Myprovince = 'city-1';
        break;
    case 7:
        $Myprovince = 'city-2';
        break;
    case 8:
        $Myprovince = 'city-3';
        break;
    case 9:
        $Myprovince = 'city-4';
        break;
    default:
        $Myprovince = 'out of borders';
}

还有一些我们可以在 PHP 中使用的其他三元运算符

简写三元运算符

$result = $initial ?: 'default';

在本例中,$result 的值将是 $initial 的值,除非 $initial 计算结果为 false,在这种情况下使用字符串 'default'

链接三元运算符

我们已经在上面的代码中使用了这种类型的三元运算符。

空合并运算符

三元运算符类似,但其行为类似于左侧操作数上的 isset,而不是仅使用其布尔值。这使得该运算符对于数组以及在未设置变量时分配默认值特别有用。

$undefined ?? 'fallback'; // 'fallback'

由于 $underfined 变量,输出将是后备

$assigned = 'foo';
$assigned ?? 'fallback'; // 'foo'

$assigned 现在有一个值,因此输出将是“foo”

另一个很棒的示例

您可以在 PHP 中使用如下所示的内容。

$output = $truthy && 'The output here';
echo $output; // The output here

请注意&&

In this type of case I always recommend to use switch case syntax. As you said it's experimental so here is the code you need to use:

$province = 9;
$Myprovince = $province == 6 ? "city-1" : (
    $province == 7 ? "city-2" : (
        $province == 8 ? "city-3" : (
            $province == 9 ? "city-4" : "out of border"
        )
    )
);
echo $Myprovince;

The output will be:

out of border because the $province is = 9

Again I recommend to use switch case. Below the code:

switch ($province) {
    case 6:
        $Myprovince = 'city-1';
        break;
    case 7:
        $Myprovince = 'city-2';
        break;
    case 8:
        $Myprovince = 'city-3';
        break;
    case 9:
        $Myprovince = 'city-4';
        break;
    default:
        $Myprovince = 'out of borders';
}

There is some other Ternary Operators that we can use in PHP

The shorthand ternary operator

$result = $initial ?: 'default';

In this case, the value of $result will be the value of $initial, unless $initial evaluates to false, in which case the string 'default' is used.

Chaining Ternary Operators

We already used this type of ternary operators in our above code.

Null Coalescing Operator

t similar to the ternary operator, but will behave like isset on the lefthand operand instead of just using its boolean value. This makes this operator especially useful for arrays and assigning defaults when a variable is not set.

$undefined ?? 'fallback'; // 'fallback'

Because of $underfined variable the output will be fallback

$assigned = 'foo';
$assigned ?? 'fallback'; // 'foo'

The $assigned has a value now so the output will be "foo"

Another Great Example

You can use something like below in PHP.

$output = $truthy && 'The output here';
echo $output; // The output here

Please note the &&

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文