My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Logical equivalence

Agnius Vasiliauskas's photo
Agnius Vasiliauskas
·May 12, 2019·

2 min read

Did you know that for expressing all logical conditions you don't need both operators of && and || ? The point is that you just need one of them,- second logical operator can be emulated and thus is just a syntax sugar for developers.

Let's write a helper function which generates a truth table for a given logical expression :

function generateTruthTable($expression) {
  $code =<<< STR
  \$input = [true, false];
  \$result = [];
  foreach (\$input as \$p) {
    foreach (\$input as \$q) {
      \$result[] = [(int)\$p, (int)\$q, (int)({$expression})];
    }       
  }
  return \$result;
STR;
  return eval($code);
}

Now, lets check logical equivalence for statements :

var_dump(generateTruthTable('$p && $q') === 
         generateTruthTable('!(!$p || !$q)')
        );

Prints TRUE, because :

$p && $q is like saying "both values are true"

!(!$p || !$q) is like saying "neither $p and neither $q is false"

In this way we can replace && operator with || and logical negation operators.

Now let's check another one example :

var_dump(generateTruthTable('$p || $q') === 
         generateTruthTable('!(!$p && !$q)')
);

Prints TRUE, because:

$p || $q is like saying "one of values is true"

!(!$p && !$q) is like saying "NOT both values are false"

In this way we can replace || operator with && and logical negation operators.

Now I hope, you will feel stronger when some language will be missing one of [AND,OR] operators. If it is missing logical negation operator too - throw it out of the window, because inversion operators are most important in the language :-)