有多少" OR"是否有限制?我可以在PHP中输入的条件?

时间:2016-10-31 16:35:58

标签: php wordpress if-statement operators

好的,所以我在WordPress中有一段代码,其中包含" OR" " elseif"内部的条件声明。这是代码:

   <?php } elseif($index == 1 || $index == 8 || $index == 9 || $index == 16 || $index == 17 || $index == 20 || $index == 21) { ?>

因此代码在$index == 20 || $index == 21

之前效果很好

我在elseif语句中使用||的次数是否有限制?

3 个答案:

答案 0 :(得分:3)

没有限制。只要确保它的可读性。

答案 1 :(得分:3)

if子句中没有OR语句的限制。请记住,您获得的OR越多,可读性就会降低。总是有一个更好的解决方案,然后只需添加越来越多的OR。

对于上面的示例,更好的解决方案是检查$ index是否在可能的值数组中,如下所示:

而不是

if ($index == 1 || $index == 2 || $index == 3) { /* ... */ }

你可以做到

if (in_array($index, [1, 2, 3])) { /* ... */ }

答案 2 :(得分:2)

请改为查看in_array()函数。这样,代码通常更紧凑,更易于同时阅读和理解:

if (in_array($id, [1, 8, 9, 16, 17]))

http://php.net/manual/en/function.in-array.php

相关问题