1

I have a super simple PHP code that looks like

$location = 'spain';

if ($location != 'usa' || $location != 'spain') {
    echo 'Not Spain';
} else {
    echo 'This is Spain';
}

I am expecting it to echo 'This is Spain' but it is not, am I using the OR operator incorrectly?

fightstarr20
  • 11,682
  • 40
  • 154
  • 278
  • 3
    http://php.net/manual/en/language.operators.logical.php ($a || $b TRUE if either $a or $b is TRUE.) – Andreas Apr 22 '18 at 14:37
  • [String comparison using == vs. strcmp](https://stackoverflow.com/q/3333353/608639) and [Logical Operators, || or OR?](https://stackoverflow.com/q/5998309/608639) – jww Apr 22 '18 at 14:42
  • 2
    Wouldn't it be easier to do `if ($location == 'spain') { echo 'This is Spain'; } else { echo 'Not Spain';}` – RiggsFolly Apr 22 '18 at 14:53

4 Answers4

1

No, you should be using AND here.

To understand why, replace the variable $location with the actual string 'spain':

if ('spain' != 'usa' || 'spain' != 'spain') {
    echo 'Not Spain';
} else {
    echo 'This is Spain';
}

You can plainly see that the first condition will be true, because "spain" is indeed not the same as "usa". That's why you're getting 'Not Spain' as a result.

rickdenhaan
  • 10,857
  • 28
  • 37
1

Probably in this case you`d want to use AND operator

if ($location != 'usa' && $location != 'spain') {
    echo 'Not Spain';
} else {
   echo 'This is Spain';
}
Basalex
  • 1,147
  • 9
  • 20
1

No its your condition is wrong.

$location = 'spain';

if ($location == 'usa' || $location != 'spain') {
    echo 'Not Spain';
} else {
    echo 'This is Spain';
}

When you use or condition then it means if any condition is true then it happen so your $location !=' usa' return true because your location value not usa it's sapin

rowmoin
  • 698
  • 2
  • 8
  • 17
0

Your conditional expression logic has unnecessary redundancy. You are performing a full string comparison and to determine if a string is spain or not, you only need one condition. (USA's got nothing to do with the logic.)

$location = 'spain';
if ($location != 'spain') {
    echo 'Not Spain';
} else {
    echo 'This is Spain';
}

If you wish to determine if the string is spain or usa and output an accurate response, using == comparisons and add an elseif expression.

$location = 'spain';
if ($location == 'spain') {
    echo 'This is Spain';
} elseif ($location == 'usa') {
    echo 'This is USA';
} else {
    echo 'This is neither Spain, nor USA';
}
mickmackusa
  • 43,625
  • 12
  • 83
  • 136