Shorthand expression for an if ( $a == $b || $a == $c ) statement

不问归期 提交于 2020-01-03 15:37:14

问题


I know this code will work:

echo ( $a == $b || $a == $c ) ? "Yes" : "No";

That can be read like:

if $a is equal to $b or $a is equal to $c

Is there a way to make it more shorter like:

if $a is equal to $b or $c

I have tried a lot including this but still no luck:

echo ( $a == ( $b xor $c ) ) ? "Yes" : "No";

回答1:


You can use in_array:

var_dump(in_array($a, [$b, $c]));

with your example:

echo in_array($a, [$b, $c]) ? 'Yes' : 'No';

Note: this syntax is only useful if you have more than 2 values. For few values $a == $b || $a == $c does the job well and is probably faster.




回答2:


These are two alternatives, but they will both take longer to execute than the code you posted because they rely on more complex functions.

preg_match('/^('.$b.'|'.$c.')$/',$a) === 0

in_array($a,array($b,$c)) === true

If you put the condition more likely to be true as the first expression, in most cases, PHP will evaluate the expression as true and not test the second expression.



来源:https://stackoverflow.com/questions/30286633/shorthand-expression-for-an-if-a-b-a-c-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!