/* A blog about frontend web development. */

PHP, Curly Brackets, and You

July 21st, 2009

Sometimes when I look at other “programmers” code I see things that make me rest my face in the palm of my hand while letting out an audible sigh.

This is one of those times. Observe:

// what follows is not good

if (isset($_GET['bacon'])) {
    $somevar = 'hamburger_'. $_GET['bacon'];
    $someothervar = $_GET['bacon'];
} else
    $somevar = 'milkshake';
    $someothervar = 'fries';

// the above is awful

Yep, you don’t need to put curly brackets (which are actually called braces) after an ‘if’ construct in PHP if you only want the next expression to be bound by it’s truthiness. The following code is perfectly valid:

if ($a > $b)
  echo "a is bigger than b";

That’s straight from the PHP Manual (which is actually pretty awesome). And everyone should know that is valid. But no one should ever use that syntax.

I didn’t write that first block of code (variable names and values have been altered to protect the guilty), so when altering that file, I had to stop and think “Did someone forget those curly brackets? Did they remove them on purpose?”. Maybe they wanted the last line to not be bound by the powers of the if-else block? The point is someones strange coding, or weird indentation, or mistake, made another programmer THINK. That takes time and I don’t like it.

The morale of the story is: never let me look at your code.