如何用PHPif/else三元求两组可能性

How to use PHP if/else Ternary for two sets of possibilities

我目前使用的是:

<?=($d === 'bar' || $d === 'foo') ? 'response' : null ?>

要创建逻辑,如果 $d 是 'bar' 和 'foo',则 return 'response' 字符串。有没有更优雅的写法?

您可以使用使用数组的方法 - 这使得它在多种情况下更具可读性:

<?= in_array($d, ['bar', 'foo']) ? 'response' : null ?>

你已经写得很优雅了。您可以使用 PHP in_array() 函数,in_array() 函数在数组中搜索特定值。

注意:如果搜索参数为字符串且类型参数设置为TRUE,则搜索区分大小写。

<?=(in_array($d, ['foo', 'bar'])) ? 'response' : null ?>

您可以改进此代码以提高可读性

<?php $foo_bar = ["foo", "bar", "bla", "blaa"]; ?>

<?=(in_array($d, $foo_bar)) ? 'response' : null ?>

在其他地方定义您的条件并将它们与 in_array() 匹配并启用严格比较 ===,如果需要的话。

$response_matches = array('foo','bar');
<?= in_array($d, $response_matches, true) ? 'response' : '' ?>