Pet peeve #1 - the comparison operator

I have a lot of pet peeves when it comes to programming, databases, web content, food, beer, and, well just about everyting. I am thinking of making a series of pet peeves here on this site. Some will seem like plain rants, and others will be more like tips.

When making comparisons, switch the order of the things you compare like this:

if ('book' == $node->type) {
  // Stuff happens
}

You might think why? And that looks weird! Yes, it does look a little weird. But I do this to not accidentially assign the $node->type the value I am comparing it with. It is hell to find an error like this when debugging:
if ($node->type = 'book') {
  // Stuff happens whether you like it or not
}

See what happened? I only put one = instead of two. PHP will not complain about this, I will just not get what I expect. If I had switched the items, PHP would have complained as I tried to assign an object to a non-variable.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd><h3>
  • Lines and paragraphs break automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.

More information about formatting options

Theme provided by Danang Probo Sayekti.