Double and Triple equals operator in PHP
Archive - Originally posted on "The Horse's Mouth" - 2006-09-12 08:31:50 - Graham EllisHave you been given a piece of code to maintain that has single, double and treble equal operators in it? What's the difference?
A single = sign is an assignment - take what's on the right as an expression and save it in the variable named on the left.
A double = sign is a comparison and tests whether the variable / expression / constant to the left has the same value as the variable / expression / constant to the right.
A triple = sign is a comparison to see whether two variables / expresions / constants are equal AND have the same type - i.e. both are strings or both are integers.
When should I use == and when ===? Here's an example.
If I write
if ($_REQUEST[name] == "") .....
then I'm testing to see if a name has been entered on a form - it will return true if no name has been enetered and it will also retrun true if there wasn't an input box on the form called "name" or if the URL was called up witghout a form at all. However, if I use the three-equals varient:
if ($_REQUEST[name] === "") .....
then this will return true if and only if the form had an input box called "name" into which the user didn't type anything at all.
Naturally, there will be times when you want to check very specifically that the form was submitted but with an empty box, and other times where you want to check simply if you've got a name or not (for whatever reason). That's why PHP has the flexibility and provides both == and ===.