Matok's PHP Blog

How to write Comparison

article image

I really often see code or variations of this:

if ($expirationDate == null) {
  // do something

What I hate about this: It will do something if $expirationDate is zero or $expirationDate is empty array or $expirationDate is empty string. The million dollar question: Is this what developer want? If yes, than fucking stop write you code like an idiot and do it correctly:

if (empty($expirationDate)) {
  // do something

In case you want really handle only one of empty values that use a === fucking strick comparison

if (null === $expirationDate) {
  // do something

I consider as good practice to use yoda conditions because it's Symfony coding standard and also I don't remeber when I write assignment by accident - but this out of this article topic.


Loose comparison is always double take and unnecessary overhead if I must analyze all code around to figure out what author really want. Try to avoid it and use strict comparison or empty function.

If you like this article then mark it as helpful to let others know it's worth to read. Otherwise leave me a feedback/comment and we can talk about it.

I'm foreigner. Where I live my friends call me Maťok.

Comments - Coming Soon