Value and Type Equality in PHP
Suppose you want to compare in such a way that a number
in quotes is not equal to the same number
without quotes. In other words, you want
to compare so that the comparison is not only
by value but also by data type. For this,
instead of the operator ==, you should use
the operator ===. Comparison with such an operator
is called strict.
See the example:
<?php
if ('3' === 3) {
echo '+++';
} else {
echo '---'; // this will work because the values are not equal by type
}
?>
But when comparing two strings '3'
the symbol '+' will be displayed on the screen:
<?php
if ('3' === '3') {
echo '+++'; // this will work
} else {
echo '---';
}
?>
The same goes for comparing numbers:
<?php
if (3 === 3) {
echo '+++'; // this will work
} else {
echo '---';
}
?>
The difference between the two operators manifests exactly when the values are the same, but the data types are different. In other cases, these operators work the same. For example, when comparing different numbers, of course, a minus will be displayed:
<?php
if (2 === 3) {
echo '+++';
} else {
echo '---'; // this will work
}
?>
Nowadays in PHP, it is generally accepted to use strict comparison everywhere. It is believed that in this case, the code is less prone to errors.
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 = 3;
if ($test1 === $test2) {
echo '+++';
} else {
echo '---';
}
?>