PHP for ColdFusion Developers – Pt 2 – Comparison Operators
In our previous lesson, we took a look at data types in PHP and how they differ from ColdFusion. In this post we’ll explore comparison operators and their relation to the data types we’ve looked at.
In ColdFusion we are used to having a couple different ways to use comparison operators, the language syntax (EQUAL) or the abbreviated syntax (EQ). In PHP we only have a single syntax, the mathematical operator.
This is the equivalent to IS, EQUAL or EQ in ColdFusion. It functions the exact same, it takes the two values, converts them to a like type and returns true if they are the same value or false if they are not.
<?php // create two variables to compare $a = true; $b = '1'; echo $a == $b; ?>
This preceding code will output ‘true’ because the values are the same. The same thing ColdFusion would do in the same situation.
This is the equivalent to IS NOT, NEQ, or NOT EQUAL in ColdFusion. Like ColdFusion it converts the variables to the same type and then compares.
<?php // create two variables to compare $a = 2; $b = '2'; echo $a != $b; ?>
This code will output ‘false’ because the variables are equal. Exactly as you would expect in ColdFusion. I hope by now you’re noticing a trend, that these comparison operators have different syntax but function the same as in ColdFusion. This is also the case for < (LESS THAN, LT), <= (LESS THAN OR EQUAL TO, LTE), > (GREATER THAN, GT), >= (GREATER THAN OR EQUAL TO, GTE). There are two comparison operators, however, that PHP offers that are not available in ColdFusion.
This is the identical operator. Unlike equal to, it does not convert the data types into a equivalent like type, but instead takes the type into account. It only returns true if the variables have the same value and type.
<?php // set two variables to compare $a = false; $b = 0; echo $a === $b; ?>
This will output false because 0 is not equal to false. If we used the equals operator this would return true. This operator is very effective for two reasons. First, since PHP is zero indexed it’s possible for a function to return a value of 0 as a location on success and a value of false when nothing is found, you want to be able to check for this. The other reason that you would use this operator is because NULL would be seen as being equal to false or 0. The identical operator helps you avoid common pitfalls that NULL may cause.
This is the ‘not identical’ operator and functions the same as Identical, except checks for items that are not identical.
<?php // set two variables to compare $a = false; $b = 0; echo $a !== $b; ?>
This will output true because these values have different types and as a result are not identical. If we used the not equal operator the output would’ve been true because they do have the same value when converted to a like type.
That’s all for this post, in the next post we’ll take a look at scoping in PHP and the differences with ColdFusion.