Comments and whitespace

You should use spaces, tabs, and new lines wherever possible to help improve readability. Operators should have a space either side, function parameters should have a space after the comma, etc. As an example, use line two rather than line one:

$foo=func($foo,$bar,$baz);
$foo = func($foo, $bar, $baz);

Furthermore, use braces even when they are optional. Without braces readability is lost, and logic errors are possible. As an example, use option two rather than option one:

/* option 1 */ if($foo == $bar) print "Foo equals bar!";

/* option 2 */ if ($foo == $bar) {
    print "Foo equals bar!";
}

Note that there is a space after the if statement in option 2 - this makes it clear that if is not any sort of function.

With regards to comments, avoid using # comments - /* */ and // are much more common, and do all that is required. Use comments throughout your code - it will help jog your memory when you come back to edit scripts months from now, and it will also help other programmers understand your code.

Many people split up complex lines of code into multiple lines, and this usually has a positive effect on readability. Although it has not been done in this book so that space is conserved, I usually pad out complex arrays and SQL queries, like this:

array(
    "foo" => "bar",
    "baz" => "wombat"
)

CREATE TABLE foo (
    ID INT NOT NULL PRIMARY KEY,
    Name CHAR(255)
);

I think you will agree that both of those are much more legible than trying to cram the same information all on one line. Remember: using lots of whitespace does not slow your scripts down one whit, so use whitespace liberally.

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Variable naming >>

Previous chapter: Coding style

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.