Skip to content

xor

Introduction

The xor keyword in PHP is used as a logical operator that returns TRUE if one of the two expressions is TRUE and the other is FALSE. If both expressions are TRUE or both are FALSE, then xor returns FALSE. This is in contrast to the or operator, which returns TRUE if either or both of the expressions are TRUE.

Example

Here's an example that demonstrates the use of xor in PHP:

Example of PHP xor keyword

php
<?php

$x = 10;
$y = 5;

if ($x > 0 xor $y > 10) {
  echo "One of the expressions is true and the other is false";
} else {
  echo "Both expressions are either true or false";
}

In the example above, the if statement will evaluate to TRUE because $x > 0 is TRUE and $y > 10 is FALSE. Therefore, the output of the code will be: "One of the expressions is true and the other is false".

It's worth noting that xor has a lower precedence than the and and or operators, so it's important to use parentheses to group expressions properly if needed.

More Information

Here's some more information about the xor operator in PHP:

  • The xor operator is also called the "exclusive or" operator because it returns TRUE only if one of the expressions is TRUE and the other is FALSE, but not if both are TRUE or both are FALSE.
  • The xor operator automatically converts its operands to boolean values before evaluation, following PHP's standard type juggling rules.
  • The xor operator can be useful in situations where you need to check that only one of two conditions is true, but not both. For example, if you have two checkboxes on a form and you want to make sure that the user selects only one of them, you can use xor to validate the input.
  • Unlike and and or, the xor operator does not short-circuit; both operands are always evaluated regardless of the first operand's value.
  • The xor operator can be combined with other operators such as == or != to create more complex expressions. For example, you can use ($x == $y) xor ($a != $b) to check that either $x is equal to $y or $a is not equal to $b, but not both.
  • Note that xor is a logical operator. For bitwise XOR operations, use the ^ operator.
  • It's worth noting that the xor operator is not commonly used in PHP programming, and you may find that you can achieve the same results using other operators or control structures. However, it can be a useful tool in certain situations where you need to perform logical operations on Boolean values.

Practice

What is the meaning of the XOR (Exclusive OR) logical operator in PHP?

Dual-run preview — compare with live Symfony routes.