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?

3

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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';
}

Comments

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

Comments

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';
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.