简体   繁体   English

PHP - 有没有更好的方法找到几个中的整数?

[英]PHP - Is there a better way find an integer out of a few?

Currently I'm using the following approach to determine if $userlevel is either 10 , 20 , or 30 . 目前我使用下面的方法来确定是否$userlevel或者是102030

if ( in_array( $userlevel, array( 10, 20, 30 ) ) ) { 

} 

Is there a better way to do this? 有一个更好的方法吗?

You are already using the "better way". 你已经在使用“更好的方式”了。 The alternative would be 替代方案是

if ($userlevel == 10 || $userlevel == 20 || $userlevel == 30) {

}

Typically you'd write a basic if statement until the number of possible values grows such that the line becomes too long, and then you move them into a collection and use in_array . 通常,您会编写一个基本的if语句,直到可能值的数量增加到该行变得太长为止,然后将它们移到一个集合中并使用in_array

If you know that $userlevel will always be one of those values, you could simply test that it's between the upper/lower bound, but this won't be any shorter than the way you're writing it now. 如果你知道$userlevel永远是这些值中的一个,你可以简单地测试它是在上限/下限之间,但是这不会比你现在编写的方式更短。

I think there is not a "better" way. 我认为没有“更好”的方式。 It depends on what you expect the values you want to choose from develop in the future. 这取决于您对未来发展中您希望选择的值的期望。 You could use a switch with no break. 你可以使用没有中断的开关。

switch ($userlevel) {
    case 10: case 20: case 30
        // ..
        break;
    default:
        // ..
}

Edit 编辑

Of course there is great benefit from the in_array solution. 当然, in_array解决方案有很大的好处。 You can store your decision array in a variable and are able to influence it from somewhere else. 您可以将决策数组存储在变量中,并且可以从其他位置影响它。

没有更好的方法与in_array进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM