-3

I am just wondering if there is any way to do something like:

if(myVar === 1|2|5) {do something} 

or

if(myVar === (1 || 2 || 5)) { do something }

which will work as

if(myVar === 1 || myVar === 2 || myVar === 5) {do something}

Using switch case is not optional solution too. Also It should work with any data type not just numbers, but strings, arrays. basically a comparison. I have already tried the first two examples and it did not work, probably it's not meant to work like that.

I am specially interested in JS and PHP, other languages are welcome for other readers.

UPDATE

"in_array" or "indexOf" or writing an inline statement is not what kind of answer i am looking for. since i know about these functions I develop for 8+ years.

Let me explain: Since I work with react I am learning JS and I have found lot of new tricks in javascript syntax like:

myArray.find(item => (item.id===something))  vs .find(function(item) {....})
const printHello = () => { return "hello" }  vs const printHello = function() { .... }
[1,2,3,4,...varWithOtherNumbers] vs concat

And lot of other tricks.

So I am just wondering if there is maybe a not well known javascript syntax trick.

Erik Kubica
  • 1,180
  • 3
  • 15
  • 39

2 Answers2

2

You can do something like this?

var a = 4;
if([1, 2, 3, 4, 5, 6, "something else"].indexOf(a) !== -1){
   console.log("It is a match!");
}

And in PHP you can use in_array

I understand it is not a shorthand and a different approach altogether but yea this do the trick!

void
  • 36,090
  • 8
  • 62
  • 107
2

PHP

$a = 5;

if(in_array($a, [1,2,3,4,5,6,7]))
{
   echo "Gotcha!";
}

Even Shorter

echo in_array($a, [1,2,3,4,5,6,7]) ? "Found you" : "Not found";

Python

this guy has something even shorter version

>>> 4 in [1, 2, 3, 4, 5] // Outputs True

Ruby

[1, 2, 3].include ? 5
Shobi
  • 10,374
  • 6
  • 46
  • 82
  • Thanks. I have updated the question to clarify what I am looking for. As i read the comments, there is no other answer for me then, that syntax like this does not exists. – Erik Kubica Feb 12 '18 at 12:48