Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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";
like image 929
5ervant - techintel.github.io Avatar asked Feb 11 '23 03:02

5ervant - techintel.github.io


2 Answers

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.

like image 82
Casimir et Hippolyte Avatar answered Feb 12 '23 16:02

Casimir et Hippolyte


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.

like image 25
user2182349 Avatar answered Feb 12 '23 18:02

user2182349