PHP如果更短的话 [英] PHP make if shorter
问题描述
什么是真正的写作方式:
if($ variable =='(value1 / value2 / value3) '){}
它应该类似于:
if($ variable =='value1'|| $ variable =='value2'|| $ variable =='value3'){}
只想缩短此代码(现在我使用 switch
)。 / p>
谢谢。
尝试 in_array()
:
if(in_array($ variable,array('value1','value2','value3'))){}
如果你碰巧有一组值,在你的例子中用 / <分隔/ code>,只需
explode()
它和你将有一个数组插入 in_array()
:
if(in_array($ variable,explode('/','value1 / value2 / value3'))){}
您可能只想使用 strpos()
因为它是一长串的值,但是不是如何处理多个值的分隔字符串(使用 explode()
代替,如上所述):
if(strpos('value1 / value2 / value3',$ variable)!== false){}
What is a true way to write like:
if ($variable == '(value1/value2/value3)' ) { }
It should work similar to:
if ($variable == 'value1' || $variable == 'value2' || $variable == 'value3') { }
Just want to make this code shorter (now I use switch
).
Thanks.
Try in_array()
:
if (in_array($variable, array('value1', 'value2', 'value3'))) {}
If you do happen to have a group of values separated by, in your example, a /
, just explode()
it and you'll have an array to plug into in_array()
:
if (in_array($variable, explode('/', 'value1/value2/value3'))) {}
It might seem like you could just use strpos()
instead since it's a long string of values, but that's not how one would work with a delimited string of multiple values (use explode()
instead, as above):
if (strpos('value1/value2/value3', $variable) !== false) {}
这篇关于PHP如果更短的话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!