在PHP中,有一种简短的方法可以将变量与多个值进行比较吗?

ver*_*ric 20 php variables comparison shorthand

基本上我想知道是否有办法缩短这样的东西:

if ($variable == "one" || $variable == "two" || $variable == "three")
Run Code Online (Sandbox Code Playgroud)

以这种方式,可以对变量进行测试,或者与多个值进行比较,而不必每次都重复变量和运算符.

例如,某些内容可能会有所帮助:

if ($variable == "one" or "two" or "three")
Run Code Online (Sandbox Code Playgroud)

或任何导致打字减少的事情.

Joh*_*nde 36

in_array() 是我用的

if (in_array($variable, array('one','two','three'))) {
Run Code Online (Sandbox Code Playgroud)

  • 对我来说太快了John Conde:P (2认同)
  • 我发布问题后,我意识到了这一点.我猜我跳了枪.这是一个非常出色的解决方案,在同时与多个事物进行比较时特别有用.谢谢.一旦网站允许我,我会接受它.它说我必须等待. (2认同)
  • 较短:`if(in_array($ variable,['one','two','three'])){` (2认同)