I have a variable $var
which must be either one or two and if it's not then throw an error
if($var != "one" && $var != "two")
{
exit('$var must be either one or two');
}
This works. However as $var
is a string and can only hold one value not both, so I'm wondering if it's not logical to write like that?
That's fine, the illogical code would be ($var == 'one' && $var == 'two')
You are checking that it's not one or two - a variable can 'not be' an endless amount of values.
if( !( $var == "one" || $var == "two" ) )
{
exit('$var must be either one or two');
}
This would be the way i would check to see if $var container either "one" or "two". As stated in other answers there is alternatives, but why over complicate things?
Its completely logical to write what you have written!
What you are writing is, IF $var is not one (which means it can still be anything else) AND IF $var is also not two (Its at this point you've ruled out both the possibilities), THEN throw the error!
Also, id recommend you to use throw new Exception('Error Message');
You can try it like this:
$possible = Array( "one", "two" );
if(!in_array($var, $possible) ) {
echo "$var can be either of: " . implode($possible, ", ");
}
This way, you can later include more values to be checked against.