What is the logical "XOR" operator in PHP? When do you use it? What does it do?

Asked

Viewed 2,531 times

8

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

2 answers

17


XOR is the operator of OR EXCLUSIVE. It is used when you want to verify the veracity of an expression OR other, exclusively.

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

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

inserir a descrição da imagem aqui

Note that if both are false or both are true, the XOR comparator will return false. It will only return true if only one of the conditions is true.

4

xor is a logical operator such as or and and. It returns true if the two operands are different, and false if the two 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 needs to select a sex, and never more than one (at least in most cases). An example in PHP:

<?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 on IDEONE.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.