Simpler Way to Check If Variable Is Not Equal to Multiple String Values

Simpler way to check if variable is not equal to multiple string values?

For your first code, you can use a short alteration of the answer given by
@ShankarDamodaran using in_array():

if ( !in_array($some_variable, array('uk','in'), true ) ) {

or even shorter with [] notation available since php 5.4 as pointed out by @Forty in the comments

if ( !in_array($some_variable, ['uk','in'], true ) ) {

is the same as:

if ( $some_variable !== 'uk' && $some_variable !== 'in' ) {

... but shorter. Especially if you compare more than just 'uk' and 'in'.
I do not use an additional variable (Shankar used $os) but instead define the array in the if statement. Some might find that dirty, i find it quick and neat :D

The problem with your second code is that it can easily be exchanged with just TRUE since:

if (true) {

equals

if ( $some_variable !== 'uk' || $some_variable !== 'in' ) {

You are asking if the value of a string is not A or Not B. If it is A, it is definitely not also B and if it is B it is definitely not A. And if it is C or literally anything else, it is also not A and not B. So that statement always (not taking into account schrödingers law here) returns true.

How do I check if a variable is not equal to multiple things in C++?

How do I check if a variable is not equal to multiple things

Is the only option to just do:

input != '1' && input != '2' && input != '3' etc etc

In the general case, for an arbitrary set of values: No, that is not the only option, but it is the simplest. And simplest is often best, or at least good enough.

If you dislike the redundant repetition of input !=, a variadic template can be used to generate the expression. I've written an example of this in another question: https://stackoverflow.com/a/51497146/2079303

In specific cases, there may be better alternatives. There exists std::isdigit for example for exactly the particular case in your example code.

In order to check if a variable is (not) equal to mutliple things which are not known until runtime, the typical solution is to use a set data structure, such as std::unordered_set.

How to test that variable is not equal to multiple things?

The while bit could be refactored a little to make it a little bit cleaner by checking if the element is within a list of choices like so

while choice not in [1, 2, 3]:

This is checking if the value of choice is not an element in that list

How do I test if a variable does not equal either of two values?

Think of ! (negation operator) as "not", || (boolean-or operator) as "or" and && (boolean-and operator) as "and". See Operators and Operator Precedence.

Thus:

if(!(a || b)) {
// means neither a nor b
}

However, using De Morgan's Law, it could be written as:

if(!a && !b) {
// is not a and is not b
}

a and b above can be any expression (such as test == 'B' or whatever it needs to be).

Once again, if test == 'A' and test == 'B', are the expressions, note the expansion of the 1st form:

// if(!(a || b)) 
if(!((test == 'A') || (test == 'B')))
// or more simply, removing the inner parenthesis as
// || and && have a lower precedence than comparison and negation operators
if(!(test == 'A' || test == 'B'))
// and using DeMorgan's, we can turn this into
// this is the same as substituting into if(!a && !b)
if(!(test == 'A') && !(test == 'B'))
// and this can be simplified as !(x == y) is the same as (x != y)
if(test != 'A' && test != 'B')

How to check if string is not equal to multiple strings

You can use a Hashtable, Dictionary or HashSet. You can store in it the strings as keys and then use the method ContainsKey()/Contains() to see if your stringParam matches any of the keys stored previously ("text1", "text2" and so on).

    HashSet<string> mySet = new HashSet<string>(); 

mySet.Add("text1");
mySet.Add("text2");
mySet.Add("text3");
mySet.Add("text4");

if (mySet.Contains(stringParam))
Console.WriteLine("It matched");

How to compare if multiple strings are not found in a statement from input variable?

Your specific error is because of using || (OR) instead of && (AND).

You want to ask "if the input isn't "word1" AND it also isn't "word2" AND it also isn't "word3"", and you can write the condition exactly like that. When you use OR, the if statement will always be true since the input can't be all 3 values at once.

Either way, I agree with Jordan that you ought to use an array.includes() for checking against many valid inputs.

PHP check value against multiple values with OR-operator

The logical ||(OR) operator doesn't work as you expect it to work. The || operator always evaluates to a boolean either TRUE or FALSE. So in your example your strings get converted into booleans and then compared.

If statement:

if($ext == ('txt' || 'rtf'|| 'log' || 'docx'))

Comes down to:

if($ext == (TRUE || TRUE || TRUE || TRUE))
if($ext == TRUE)

To solve this problem and get the code to work as you want it to you can use different methods.

Multiple comparison

One way to solve the problem and check your values against multiple values is, to actually compare the value against multiple values:

if($ext == "txt" || $ext == "rtf" /* || ... */)

in_array()

Another way is to use the function in_array() and check if the value is equal to one of the array values:

if(in_array($ext, ["txt", "rtf" /* , ... */], TRUE))

Note: Second parameter is for strict comparison

switch()

You could also use switch to check your value against multiple values and just let the case fall through.

switch($ext){

case "txt":
case "rtf":
/* case ...: */
$pClass = "text-";
break;

}

Is there a way to check if a string is not equal to multiple different strings?

Just build a collection - if it's small, just about any collection will do:

// Build the collection once (you may want a static readonly variable, for
// example).
List<string> list = new List<string> { ".jpg", ".jpeg", ".gif", ".bmp", ... };

// Later
if (list.Contains(extension))
{
...
}

That does loop over all the values of course - but for small collections, that shouldn't be too expensive. For a large collection of strings you'd want to use something like HashSet<string> instead, which would provide a more efficient lookup.



Related Topics



Leave a reply



Submit