合并 elseifs [duplicate]

Combine elseifs [duplicate]

提问人:Job82 提问时间:10/9/2023 最后编辑:SimplyInkJob82 更新时间:10/11/2023 访问量:62

问:

这可能是一个愚蠢的问题,但我未能将多个 .我相信一定有更聪明的方法。你有想法吗?elseif

<?php
$level_ids = leaky_paywall_subscriber_current_level_ids();

if (!empty($level_ids)) {
    if (in_array(2, $level_ids)) {
        echo 'DO THIS';
    } elseif (in_array(3, $level_ids)) {
        echo 'DO THIS';
    } elseif (in_array(4, $level_ids)) {
        echo 'DO THIS';
    } elseif (in_array(6, $level_ids)) {
        echo 'DO THIS';
    } elseif (in_array(7, $level_ids)) {
        echo 'DO THIS';
    } elseif (in_array(9, $level_ids)) {
        echo 'DO THIS';
    } elseif (in_array(10, $level_ids)) {
        echo 'DO THIS';
    } else {
        echo 'DO THAT';
    }
}

我试图更聪明地结合起来,但它不起作用。

非常感谢您的帮助!

php if-语句

评论

0赞 GrumpyCrouton 10/9/2023
如果这些陈述中多个为真怎么办?您当前的代码将只在第一个匹配项上运行DO THIS

答:

-1赞 scott8035 10/9/2023 #1

你写它的方式没有错。我会根据 One True Brace 样式对代码的格式略有不同,但那是因为我一直存在:

if (...) {
  echo 'DO THIS';
} elseif (...) {
  echo 'DO THIS';
} else {
  echo 'DO THAT';
}
-2赞 lukas.j 10/9/2023 #2
if ([] === array_intersect([ 2, 3, 4, 6, 7, 9, 10 ], leaky_paywall_subscriber_current_level_ids())) {
  echo 'DO THAT';
} else {
  echo 'DO THIS';
}

评论

1赞 mickmackusa 10/11/2023
正如我最近一直在向你重复的那样,请停止在 Stack Overflow 上发布纯代码答案。