# Shorter code for an If statement testing a variety of matches

How can I shorten these two If expressions into one

 variable="hello";
If[variable=="hi", Print["hi there"]];
If[variable=="hello", Print["hi there"]];


Longhand shortening:

 If[variable=="hello" || variable=="hi", Print["hi there"]];


to something like this:

 If[variable=={"hello","hi"}, Print["hi there"]];

• Use MemberQ[{"hello","hi"}, variable] – Coolwater May 4 '18 at 21:02
• And if you have to test against many different conditions, Which and Switch might be helpful. – Henrik Schumacher May 5 '18 at 6:49

If[MemberQ[{"hi", "hello"}, variable], Print["hi there"]];


Should do the trick. List membership is usually the same as equivalence, and it should always be the same with strings.

Since it was mentioned in the comments, StringMatchQ would work quite well if your strings had more in common with each other. As it stands, it's just a binary pattern:

If[StringMatchQ["hello", "hello" | "hi"], Print["hi there"]];


Which works, but clearly isn't leveraging the full potential of a pattern matching functions. It'd be more applicable if you were matching to a much larger set of fairly similar strings.

• Nice. Thanks. I was just looking at StringMatchQ, but I think MemberQ is a safer choice. – Tom Mozdzen May 4 '18 at 21:05
• @TomMozden It's perfectly applicable here, but it seems like a waste to me for this problem. If you were comparing a much larger set of very similar strings, I think it'd be much more useful. – eyorble May 4 '18 at 21:09
• I have a list of 10+ items in my real program. I just mentioned two here to illustrate what was needed. – Tom Mozdzen May 4 '18 at 21:10
• If they have sufficient similarity to be amenable to pattern matching, go for it. I'd think it's more applicable when you have enough items that you start resorting to combinatorics to count them though. – eyorble May 4 '18 at 21:11

You can also do it with MathchQ and Alternative ( ] ).

If[MatchQ[#, "hello" | "hi"], "hi there", "no match"] & /@ {"hello", "hi", "g'day"}


{"hi there", "hi there", "no match"}