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 evaluate to TRUE
, xor
evaluates to TRUE
only if either its left operand or its right operand evaluate 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
We’ll tolerate many ingredients in a pie, but having both bananas and chicken is something we simply can’t condone. And… yet… I must have either bananas or chicken in any pie I eat.
Write a function, eatPie()
. Your function should have a single parameter, an array of ingredients. If the array includes either "chicken"
or "bananas"
(but not both), your function should return "Delicious pie!"
. Otherwise, it should return "Disgusting!"
.
You should use xor
to accomplish this task.
We’ve provided a couple arrays for you to test your function with. Invoke your function once with the $banana_cream
ingredients array and once with the $experimental_pie
. Use echo
to print the results to the terminal. Make sure it’s working as expected!