UltraMega Blog

10 Common PHP Mistakes to Avoid

These are some very common mistakes that are made in PHP. Some of these can be tricky to catch and can lead to all sorts of strange behavior. So here are 10 common PHP coding mistakes to avoid.

1 '=' Vs. '=='

Using a single '=' in a comparison will cause an assignment and return true, so this mistake can have some pretty unexpected results. It can be hard to catch since it looks perfectly valid to the interpreter if you are comparing something with a variable.

An easy way to avoid this is to swap the subject and variable like this:

if(true = $something) { // Parse error!
   // do stuff

The above will result in a parse error since you can't assign a literal to something, making it easy to catch and fix.

2 '==' Vs. '==='

There is a big difference between the '==' (equal) and '===' (identical) comparison operators. '==' will convert types to match before making the comparison, while '===' will compare directly without converting. So in situations where the difference between '0' and 'false' matters, you must use '==='. Here's some examples:

var_dump(false == 0); // true
var_dump(false === 0); // false
var_dump(false === false); // true
var_dump('0' == 0); // true
var_dump('0' === 0); // false