Coding De Morgan’s Laws

Learn to code De Morgan's laws in the PHP and Java languages.

Introduction to De Morgan’s laws

In this lesson, we’ll learn about De Morgan’s laws based on Boolean algebra and logical expression.

Augustus De Morgan was a contemporary mathematician of George Boole. Although he didn’t create the laws using his name, they are credited to him because he was the creator.

De Morgan’s laws are based on Boolean algebra, and in every programming language, they’re widely applied and equally valid. The rule states that we can write the way we see below, where a and b are two boolean values (true or false):

Press + to interact
not (a and b) evaluates to (not a) or (not b)
not (a or b) evaluates to (not a) and (not b)

Let’s code De Morgan’s laws in PHP and Java.

Coding the first of De Morgan’s laws in PHP

Let’s apply this law in PHP. We’ll see the code first:

Press + to interact
//DeMorganOne.php
<?php
// not (a and b) evaluates to (not a) or (not b)
class DeMorganOne{
public $numOne;
public $numTwo;
public function notAandB($paramOne, $paramTwo) {
$this->numOne = $paramOne;
$this->numTwo = $paramTwo;
$additionOfTwoNumbers = $this->numOne + $this->numTwo;
//not(paramOne and paramTwo)
if(!($this->numOne >= 10 && $this->numTwo <= 15)){
echo "Addition of two numbers : $additionOfTwoNumbers";
} else {
echo "The first number is greater than or equal to 10, and the second number is less than or equal to 15.";
}
}
public function notAORnotB($paramOne, $paramTwo) {
$this->numOne = $paramOne;
$this->numTwo = $paramTwo;
$additionOfTwoNumbers = $this->numOne + $this->numTwo;
//(not paramOne) or (not paramTwo)
if(!($this->numOne >= 10) || !($this->numTwo <= 15)){
echo "Addition of two numbers : $additionOfTwoNumbers";
} else {
echo "The first number is greater than or equal to 10, and the second number is less than or equal to 15.";
}
}
}
$firstCase= new DeMorganOne();
$secondCase= new DeMorganOne();
$firstCase->notAandB(11,14);
echo"\n";
$firstCase->notAandB(1,140);
echo"\n";
$secondCase->notAORnotB(11,14);
echo"\n";
$secondCase->notAORnotB(1,140);

We’ve tested the first law by successfully passing the same value through two class variables and methods and we’ve obtained the same result:

//DeMorganOne.php
The first number is greater than or equal to 10, and the second number is less than or equal to 15.
Addition of two numbers : 141
The first number is greater than or equal to 10, and the second number is less than or equal to 15.
Addition of two numbers : 141

Now, we can play around by successfully passing different values to see how this law works. Whatever values we pass, they must be the same for two-member methods, and we will get the same result.

In the code above:

  • Line 5: We declare the DeMorganOne class.

  • ...