The forgotten PHP logical operator

It is very rare that I have seen some code that employs the PHP XOR logical operator. It is not the case that it is not required or programmers are unfamiliar with it; it probably seems that most programmers have become comfortable with using the more common ‘&&’ and ‘||’ operators to construct all logical comparisons; the XOR operator relegated to the subconscious black hole.

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 = 'download_A';
$dir2 = 'download_B';
 
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 = 'download_A';
$dir2 = 'download_B';
 
if(is_dir($dir1) XOR is_dir($dir2)) {
    echo "Only one Directory exists!";
}
 
?>


4 thoughts on “The forgotten PHP logical operator

  1. xor and != are the same for boolean expressions.

    I don’t know if the two have different precedence in PHP.

  2. interesting discussion. what happens here?
    if($a AND $b XOR $c AND $d){

    is it the same as this?
    if(($a AND $b) != ($c AND $d)){
    or this?
    if($a AND ($b != ($c AND $d))){

Comments are closed.