What is the logical operator "XOR" in PHP? When to use it? What he does?


I wonder what this XOR operator is? When to use it? And what does it do in PHP?

asked by anonymous 22.01.2015 / 16:24

2 answers


XOR is the EXCLUSIVE OU operator. It is used when you want to check the veracity of an expression OR else, exclusively.

Example: I have 2 hours per week to study either PHP or JAVA.

In this case, we are talking about exclusive operator. Or one or the other, never both.

Notice that if both are false or both are true, the XOR comparator will return false. It will only return true with only one of the conditions being true.

22.01.2015 / 16:31

xor is a logical operator such as or and and . It returns true if both operands are different, and false if both are equal, both true and false.

A practical example is when you need a field to be selected, but never two at the same time, as in the case of sex: The user must select a gender, and never more than one (at least in the majority of cases) . An example in PHP:

  $masculino = true;
  $feminino  = false;

  if ($masculino xor $feminino) {
    print("Correto! Um sexo foi escolhido");
  } else {
    print("ERRO! Nenhum ou ambos sexos foram escolhidos.");

See working at IDEONE .

22.01.2015 / 17:25