Avoiding If Statement Typos In PHP

It is very easy to break a program with a simple typo. Instead of typing == when comparing two values you type = and actually assign a variable. This is an easy way to introduce a bug as you will not always notice it until your program doesn't work. There is an easy way of avoiding this.

By using the following syntax:

if(100 == $score){ }

Instead of the usual format:

It is very easy to break a program with a simple typo. Instead of typing == when comparing two values you type = and actually assign a variable. This is an easy way to introduce a bug as you will not always notice it until your program doesn't work. There is an easy way of avoiding this.

By using the following syntax:

if(100 == $score){ }

Instead of the usual format:

if($score == 100){ }

You can spot a typo when it happens as putting the number on the left hand side produces a parse error. The following will assign 100 to the $score variable instead of seeing if 100 and $score are the same.

if($score = 100){ }

The following will produce a syntax error.

if(10 = $score){ }

This makes spotting these sort of problems very easy.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
12 + 6 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.