Non-Strict Comparison of Boolean Values in PHP
In the previous example, I used the
=== operator for comparison.
In this case, our variable was compared
for equality with true
both by value and by type.
In our task, the
== operator can also be used.
If the variable test
always contains one of the values true
or false, then nothing will change:
<?php
$test = true; // here we write either true or false
if ($test == true) {
echo '+++';
} else {
echo '---';
}
?>
But if any values can be assigned to the variable $test,
then everything becomes
much more complicated. In such a case, if the variable
contains a non-boolean value, that value
will first be converted to a boolean and only
then will be compared.
Let's say, for example, the variable contains
the number 1. In this case, it will first
be converted to the boolean type, that is,
to true. And then the comparison will be performed:
<?php
$test = 1;
if ($test == true) {
echo '+++'; // this will trigger, because 1 == true is correct
} else {
echo '---';
}
?>
Whereas, for example, the number 0 converts
to false. And our condition will ultimately
be false:
<?php
$test = 0;
if ($test == true) {
echo '+++';
} else {
echo '---'; // this will trigger, because 0 == true is NOT correct
}
?>
Without running the code, determine what will be displayed on the screen:
<?php
$test = 1;
if ($test == true) {
echo '+++';
} else {
echo '---';
}
?>
Without running the code, determine what will be displayed on the screen:
<?php
$test = 0;
if ($test == true) {
echo '+++';
} else {
echo '---';
}
?>
Without running the code, determine what will be displayed on the screen:
<?php
$test = 1;
if ($test == false) {
echo '+++';
} else {
echo '---';
}
?>
Without running the code, determine what will be displayed on the screen:
<?php
$test = 1;
if ($test != true) {
echo '+++';
} else {
echo '---';
}
?>
Without running the code, determine what will be displayed on the screen:
<?php
$test = '';
if ($test == false) {
echo '+++';
} else {
echo '---';
}
?>
Without running the code, determine what will be displayed on the screen:
<?php
if ($test == true) {
echo '+++';
} else {
echo '---';
}
?>