1

# Comparisons in PHP

Something that I just learned is that in PHP we can determine the stiffness of our comparisions and we can do this according to the number of equal signs that we use (=).

At this point you need to know that there are different types of values, such as string, integer, real, double, boolean, etc. But PHP can tell us that “9” is equal to 9 if we use ==, but if we use three === the stifness is harder and PHP will tell us something different. For example:

``````<?php
\$integer = 9;
\$string = "9";

if(\$integer == \$string){
echo "\$integer is equal to \$string \n";
}else{
echo "\$integer is not equal to \$string \n";
}
?>
``````

In this case the result will be:
9 is equal to 9
But if we do the same with 3 plus signs instead of only two as in the example below:

``````<?php
\$integer = 9;
\$string = "9";

if(\$integer === \$string){
echo "\$integer is equal to \$string \n";
}else{
echo "\$integer is not equal to \$string \n";
}
?>
``````

The result will be the following
9 is not equal to 9

As well we have the comparison operators useful to determine if something is different to other thing. These are:

• != this only determine the value, without take into account the type of value
• !== this is stiffer because it take into account the type of value

We can see this in the followin example:

``````<html>
<title>This is a sample</title>
<body>
<?php
\$integer = 9;
\$string = "9";

if(\$integer != \$string){
echo "\$integer is different to \$string \n";
}else{
echo "\$integer is equal to \$string \n";
}
?>
</body>
</html>
``````

Here the PHP code is embedded into a html file. The point here is that the two variables have the same value but they are not exactly the same because one of them is a string and the other is an integer. The result of this code is the following:

``<html><head><title>This is a sample</title></head><body>9 is equal to9</body></html>``

But if we use the comparison operator !==, which is stiffer, we get the next code and result:

Code

``````<html>
<title>This is a sample</title>
<body>
<?php
\$integer = 9;
\$string = "9";

if(\$integer !== \$string){
echo "\$integer is different to \$string \n";
}else{
echo "\$integer is equal to \$string \n";
}
?>
</body>
</html>
``````

And the result

``<html><head><title>This is a sample</title></head><body>9 is different to9</body></html>``

Last but not least, there are others comparison operators:

• <= Less than or equal to…
• >= Greater than or equal to…
• < Less than
• > Greater than
Escribe tu comentario
+ 2