Monday, 20 August 2012

Know the Difference Between Comparison Operators


Equality Operators 4
PHP’s list of comparison operators.
Comparison operators are a huge part of PHP, and some programmers may not be as well-versed in their differences as they ought. In fact, an article at I/O reader 5 states that many PHP developers can’t tell the differences right away between comparison operators. Tsk tsk.
These are extremely useful and most PHPers can’t tell the difference between == and ===. Essentially, == looks for equality, and by that PHP will generally try to coerce data into similar formats, eg: 1 == ‘1′ (true), whereas === looks for identity: 1 === ‘1′ (false). The usefulness of these operators should be immediately recognized for common functions such as strpos(). Since zero in PHP is analogous to FALSE it means that without this operator there would be no way to tell from the result of strpos() if something is at the beginning of a string or if strpos() failed to find anything. Obviously this has many applications elsewhere where returning zero is not equivalent to FALSE.
Just to be clear, == looks for equality, and === looks for identity. You can see a list of the comparison operators on the PHP.net website.

No comments:

Post a Comment