Inequality by Value and Type in PHP
In addition to the operator !=, there is also
the operator !==, which takes type into account during
comparison. Let's look at the differences between
them with examples.
Suppose two numbers 3 are compared
using the operator !=. This operator compares
values for being NOT equal. Since
our values are indeed equal, '-' will be
displayed:
<?php
if (3 != 3) {
echo '+++';
} else {
echo '---'; // this will execute because the values are equal
}
?>
Now suppose one of our values is
in quotes. In this case, the operator !=
will still consider them equal (since the
value matches, and the type is not important for this operator)
and will again output '-':
<?php
if ('3' != 3) {
echo '+++';
} else {
echo '---'; // this will execute because the values are equal
}
?>
Let's now compare two numbers 3
using the operator !==. It will also
consider them equal and output '-':
<?php
if (3 !== 3) {
echo '+++';
} else {
echo '---'; // this will execute because the values are equal
}
?>
But if we now put one of the threes in quotes,
the operator !== will consider our threes
unequal, because, although their values match,
they have different types:
<?php
if ('3' !== 3) {
echo '+++'; // this will execute because the values are NOT equal
} else {
echo '---';
}
?>
Without running the code, determine what will be displayed on the screen:
<?php
$test1 = '3';
$test2 = '3';
if ($test1 != $test2) {
echo '+++';
} else {
echo '---';
}
?>
Without running the code, determine what will be displayed on the screen:
<?php
$test1 = '3';
$test2 = '3';
if ($test1 !== $test2) {
echo '+++';
} else {
echo '---';
}
?>
Without running the code, determine what will be displayed on the screen:
<?php
$test1 = 3;
$test2 = '3';
if ($test1 != $test2) {
echo '+++';
} else {
echo '---';
}
?>
Without running the code, determine what will be displayed on the screen:
<?php
$test1 = 3;
$test2 = '3';
if ($test1 !== $test2) {
echo '+++';
} else {
echo '---';
}
?>
Without running the code, determine what will be displayed on the screen:
<?php
$test1 = 3;
$test2 = 2;
if ($test1 !== $test2) {
echo '+++';
} else {
echo '---';
}
?>