Learn

The logical operator xor stands for exclusive or. It takes two different boolean values or expressions as its operands and returns a single boolean value. Unlike regular or which evaluates to TRUE if either its left operand or its right operand evaluates to TRUE, xor evaluates to TRUE only if either its left operand or its right operand evaluates to TRUE, but not both.

TRUE xor TRUE; // Evaluates to: FALSE FALSE xor TRUE; // Evaluates to: TRUE TRUE xor FALSE; // Evaluates to: TRUE FALSE xor FALSE; // Evaluates to: FALSE

We can use xor to answer either/or questions: Did you wear either glasses or contacts today?

  • If neither, the answer is “No”—I didn’t wear glasses nor did I wear contacts. My vision is impaired.
  • If I wore both, the answer is “No”—I didn’t wear either glasses or contacts. My vision is impaired.
  • If I wore contacts, the answer is “Yes”—I wore contacts, so my vision was corrected.
  • If I wore glasses, the answer is “Yes”—I wore glasses, so my vision was corrected. .

Let’s code up this example:

$is_wearing_glasses = TRUE; $is_wearing_contacts = TRUE; if ($is_wearing_glasses xor $is_wearing_contacts){ echo "Your vision is corrected!"; } else { echo "Your vision is impaired."; }

Let’s practice!

Instructions

1.

We need to have a balanced meal, but having both bananas and chicken in one sitting is something we simply can’t condone. And… yet… I won’t sit down to eat unless the meal has either bananas or chicken.

Create an if statement that checks if either the fruit is "banana" or the protein is "chicken". If the statement is true, then use echo to print the string "Dig in!".

Remember, we want don’t want both, just one, so use xor to accomplish this task.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?