Hi all,
Here is a little tip that I wish someone had told me when I started out with PHP
As I'm sure you all know, when comparing two values you would commonly use something like:
PHP Code:
if ($myVar == 'hello')
{
// ...
}
However, if you are anything like me, you will occasionally type a single equals sign instead of double:
PHP Code:
if ($myVar = 'hello')
{
// ...
}
Which introduces an anoying little hard-to-find bug in your code as instead of comparing the 2 values, it is actually setting
$myVar to 'hello'!
Unfortunately, PHP sees this as perfectly valid so you don't get any error messages and aren't aware of any problems until it causes a bug in your application.
However, there is a little trick you can use to prevent this problem. When comparing values, use:
PHP Code:
if ('hello' == $myVar)
{
// ...
}
As you can see, we have reversed the variables. This is still a perfectly valid
if() statement but if you accidently type a single equals sign instead of two equals signs:
PHP Code:
if ('hello' = $myVar)
{
// ...
}
PHP will throw you a nice error letting you know of the problem:
Code:
Parse error: syntax error, unexpected '=' in ...
Once you get in to the habbit of writing your comparisons this way it will save you countless hours of debugging anoying little bugs (well, it has for me anyway

)
Alan