#native_company# #native_desc#

Best Practices: PHP Coding Style Page 2

By Tim Perdue
on January 3, 2001


All your code should be properly indented. This is the most fundamental
thing you can do to improve readability. Even if you don’t comment your
code, indenting will be a big help to anyone who has to read your code
after you.
while ($x < $z) {
	if ($a == 1) {
		echo 'A was equal to 1';
	} else {
		if ($b == 2) {
			//do something
		} else {
			//do something else
The PEAR RFC standard calls for 4 spaces, not tabs of any size, in your code.
I disagree with this personally and will continue to tab my code. My view is
that tabs rather than spaces will create smaller files and smaller files are
faster to parse, upload, download, etc etc. The other advantage to using tabs
is that you can set your tab size to your personal preference when viewing
someone else’s code. I used to use 8-space tabs, but recently switched to
4-space tabs and all my code “reformatted” automatically by just setting a
preference in vim.

Control Structures

This is pretty much common sense, but I still see an awful lot of code
that is not braced for readability. If you use conditional expressions (IF statements)
without braces, not only is it less readable, but bugs can also be introduced when
someone modifies your code.
Bad Example:
if ($a == 1) echo 'A was equal to 1';
That’s pretty much illegible. It may work for you, but the person following
after you won’t appreciate it at all.
Less Bad Example:
if ($a == 1) 
	echo 'A was equal to 1';
Now that’s at least readable, but it’s still not maintainable. What if I want
an additional action to occur when $a==1? I need to add braces, and if I forget
to, I’ll have a bug in my code.
if (($a == 1) && ($b==2)) {
	echo 'A was equal to 1';
	//easily add more code
} elseif (($a == 1) && ($b==3)) {
	//do something
Notice the space after the if and elseif – this helps distinguish
conditionals from function calls.