Logical Operations in PHP
Let's look at the following code:
<?php
$a = 1;
$b = 2;
if ($a == $b) {
var_dump(true);
} else {
var_dump(false);
}
?>
As you can see, this code compares
variables a and b
and, if they are equal, it outputs
true to the console, and if not - then false.
It's time to reveal something
non-obvious to you: in fact, the
if construct is not mandatory for comparison
- the operators themselves like ==, ===, !=, <, > and
others return either true,
or false as their result.
See the example:
<?php
var_dump(1 == 1); // will output true
var_dump(1 == 2); // will output false
?>
Based on the above, the code from the beginning of the lesson can be rewritten in a simpler way:
<?php
$a = 1;
$b = 2;
var_dump($a == $b);
?>
You can not output the result immediately, but assign it to some variable:
<?php
$a = 1;
$b = 2;
$res = $a == $b;
var_dump($res);
?>
Given the following variables:
<?php
$a = 2 * (3 - 1);
$b = 6 - 2;
?>
Using the == operator, find out if
the values of these variables are equal or not.
Given the following variables:
<?php
$a = 5 * (7 - 4);
$b = 1 + 2 + 7;
?>
Using the > operator, find out if
variable $a is greater than $b.
Given the following variables:
<?php
$a = 2 ** 4;
$b = 4 ** 2;
?>
Using the != operator, find out if
the values of these variables are different or not.