What is php XOR Logical operation

The XOR operation is used to test if one value of the two variable is true and but both two are NOT.

You probably won’t need this one too much. But it’s used when you want to test if one value of two is true but NOT both. If both values are the same, then PHP sees the expression as false. If they are both different, then the value is true. Suppose you had to pick a winner between two contestants. Only one of them can win. It’s an XOR situation!

$one = "won";
$two = "won";

if ($one XOR $two) {
echo "Only one winner!";
}
 else {
echo "Both can't win!";
}

See if you can guess which of the two will print out, before running the script.

Only one winner!

Real time example

Take the following artificial example. We want to check if only one of the directories – either ‘$dir1′ or ‘$dir2′, but not both exists. The code using only the logical ‘&&’ , ‘||’ and ‘!’ operators is shown below.

<?php
$dir1 = 'url1';
$dir2 = 'url2';
 
if((is_dir($dir1) && !is_dir($dir2)) || (!is_dir($dir1) && is_dir($dir2))) {
    echo "Only one Directory exists!";
}
?>

The code obviously looks confusing, which we could easily simplify using the ‘XOR’ operator as given below. The code is concise, easier to understand, and the chances of introducing bugs is smaller than the previous version.

<?php
 
$dir1 = 'url1';
$dir2 = 'url2';
if(is_dir($dir1) XOR is_dir($dir2)) {
    echo "Only one Directory exists!";
}
?>