在 php 中编码的更简单方法“if ( $x == $a[1] || $x == $a[2] || $x == $a[3] ....)
正如标题所述,有什么更简单的方法来做
if ( $somevariable == $somearray[1] || $somevariable == $somearray[3] || $somevariable == $somearray[10] )
似乎即使有 3 个变量..也会有一个快捷方式。
我知道这不起作用,但类似的东西会很好:
if ($somevariable == $somearray[1],$somearray[3],$somearray[10]) {
As the title states, whats a more simple way to do
if ( $somevariable == $somearray[1] || $somevariable == $somearray[3] || $somevariable == $somearray[10] )
Seems like even with 3 variables.. there would be a shortcut.
I know this doesnt work, but something like would be nice:
if ($somevariable == $somearray[1],$somearray[3],$somearray[10]) {
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一种选择
One option
您可以使用 in_array。
You could use in_array.
其实你的代码已经没问题了。
如果您不想深入重构,请保持原样。因为:
在追求简洁的同时,不要忘记可读性。
唯一可接受的解决方案是可读性不低于当前解决方案的解决方案。 读起来(字面意思:如果你大声朗读)就像它的意图一样。
示例:通过创建这样的函数,
您可以稍后以这种方式调用它,
同时保持简洁性和可读性(如果您命名正确)。
正如评论中提到的,参数似乎有点多余。这取决于。如果它是一个函数,请将它们保留在适当的位置。
如果此函数将成为某个适当的类的方法 - 您可以省略它们,使其成为
In fact, your code is already all right.
If you don't want to dive into depths of refactoring, just leave it as is. Because:
In pursue for conciseness, you should not forget readability.
The only solution acceptable is one which no less readable than your current one. Which reads (literally: if you read it aloud) like it's intentded.
Example: by making such a function,
you can call it later this way,
keeping both conciseness and readability (if you name it properly).
As it was mentioned in comments, parameters seems a bit redundant. it depends. if it's going to be a function, keep them in place.
if this function going to be a method of some appropriate class - you can omit them, making it
另一种选择使用
array_intersect_key()
:如果您有大量索引需要检查,这非常有用。
在可变参数函数中,正如 @knittl 建议的那样:
Another option using
array_intersect_key()
:This is mostly useful if you have a large numbers of indexes to check.
In a variadic function, as @knittl suggested: