0

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
  • 10,259
  • 33
  • 132
  • 247
  • 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 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
  • 640
  • 1
  • 8
  • 17
0

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
  • 9,913
  • 25
  • 34
0

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
  • 957
  • 8
  • 18
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
  • 37,596
  • 11
  • 75
  • 105