Described herein are my personal PHP coding standards, and while they they are largely a matter of personal taste and aesthetics, I would also like to make a case for each of the major conventions (and hopefully win a few converts! :)

While this document is PHP-specific in content, it’s language-agnostic in principle, and most of these conventions I follow regardless of whether I’m coding in PHP, Perl, or C.

Whitespace

One of my biggest pet-peeves is whitespace. Use the ‘tab’ key to indent each block level, and make sure that your editor is using tabs, not spaces! If your tabstops aren’t to your liking, then adjust your tabstops, don’t use spaces.

Why: Tabs tend to align more uniformly across systems, fonts, and editors than spaces do, which helps ensure readability across environments.

Single vs. Double Quotes

Always use single-quotes when the string being quoted doesn’t need to be evaluated.

Why: Even if there’s nothing inside your string that needs to be handled by the string parser, when you use double quotes, it goes through that parser anyway. Single quotes don’t, which improves efficiency. Caveat! Escaped characters like ‘\n’ don’t get evaluated inside single quotes either, so be careful.

Operand Ordering

When performing logic tests against constant operands, always place the constant on the left side of the equation:

if( 'test' == $mode )

Why: If you miss an ‘=’ in your code, it will produce an error, as opposed to silently passing your logic. “$mode = test” will always return true, and can lead to the occasional yet insidious bug.

Braces

Ok, this one is almost purely just my personal preference.

Braces should always-always-always be on their own line, especially when the opening logic statement is lengthy, convoluted, or spans multiple lines.
if( some_criteria && some_other_criteria ||
( some_really_long_criteria != ( some_other_really_long_criteria !== some_criteria )))
{
    do_stuff();
    do_other_stuff();
}

There’s no benefit to doing this one way or the other, just that I find it more legible (and most people I know, after doing things this way for awhile, tend to agree, despite initial reservations/outright hatred. Try it for a week, really!)

Exception: Don’t use braces for single-line logic blocks; it’s too much clutter. Just be sure to use proper indenting.

Parenthesis

Again, purely aesthetic. When parenthesis are in use, pad out the parenthesis from their content. Again, improves legibility, particularly after a long day. Also, keep spaces between individual components. I personally prefer to snug the left-most paren right up next to the logic operator or function name, but I’m less picky about this.


if( $foo || $bar )

not

if($foo||$bar)