Have 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 ===.
(written 2006-09-12)
Associated topics are indexed under
H104 - PHP - Control Statements [3397] Does a for loop evaluate its end condition once, or on every iteration? - (2011-08-18)
[3200] How a for loop works Java, Perl and other languages - (2011-03-12)
[2912] Predictions for the seagull population - (2010-08-09)
[2304] Extracting real data from an exported file in PHP or Perl - (2009-07-25)
[1825] Question Mark - Colon operator (Perl and PHP) - (2008-10-08)
[1696] Saying NOT in Perl, PHP, Python, Lua ... - (2008-07-04)
[1477] Decisions - small ones, or big ones? - (2007-12-18)
[1220] for loop - how it works (Perl, PHP, Java, C, etc) - (2007-06-06)
[1199] Testing for one of a list of values. - (2007-05-22)
[1191] Smart English Output - via PHP and Perl ? : operator - (2007-05-18)
[962] Breaking a loop - Ruby and other languages - (2006-12-03)
[657] The ternary operator in Python - (2006-03-25)
[421] Don't repeat code - use loops or functions - (2005-08-21)
[406] Assignment, equality and identity in PHP - (2005-08-08)
[353] Wimbledon Neck - (2005-06-20)
[340] Code and code maintainance efficiency - (2005-06-08)
Some other Articles
Being sure to be positive in PerlA lazy programmer is a good programmerCatching the slopeAdd to shopping cart - NO VACANCIES signDouble and Triple equals operator in PHP4 weeks to goBallooning from DevizesWarning - false emails, said to be from PaypalPut the answer in context - it may be printedFrom the Manor written