LanguagesPHPPHP Coding Style and Organization

PHP Coding Style and Organization content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Generally, programming is considered as something that happens behind the scenes; something that has more to do with function than form. Programmers frequently leave the appearance of the application up to a designer, so the idea of style having anything to do with coding can seem a little laughable at first. After all, as long as the logic and syntax of a PHP script is correct, the computer knows what we mean, and our script works. The computer doesn’t care what the actual code looks like, only what it says.

But the computer only processes scripts; people are the ones who conceive and author them. Besides just “working,” it is essential that an application is maintainable, re-usable, and most importantly, expandable. It has to be readable and understandable not only to the person who authored it, but to other people as well.

In this article, you’ll find some general ideas on the elements of good programming style, quick tips for achieving it, and also some thoughts on how to organize the code within your scripts.

Comment Your Code

Comments are worth mentioning first, because their usage is the single most important aspect of coding style. Ironically, it also seems to be the one rule of good style that everyone forgets either by accident, or by tacit decision that it’s really more effort than it’s worth.

Comments, however, exist for a valuable reason. Even the most logically coded script is still, essentially, written in a foreign language of variables, loops, and functions. Comments give you a road map to what’s happening in the script at any point and time. This is not so important while you are writing the script, because much of the material is fresh in your mind. It is, however, a life saver if you ever need to return to something you wrote several months ago. Spending a half hour attempting to understand what you wrote before you can actually accomplish anything is always a bad situation to be in.

Because coding methods can vary from programmer to programmer, comments also aid in making your programming instantly more understandable to anyone else who needs to access it. In multi-developer environments, this is essential to being able to effectively share or hand code down to another programmer.

Commenting your code is also good method of re-affirming your understanding how your own script works. When dealing with particularly complex applications, it is easy to lose track of the logic or flow of the script. Including comments on what each piece of code does not only encourages you to think about what’s happening, but can often highlight problems or potential bugs along the way.

Indent Your Code

Commenting your code goes a long way to making it more understandable, but what about making it more readable? Take a look at the following two snippets of PHP, both of which produce the same output (this code snippet dynamic generates form fields based on information pulled from a database). Which is actually easier to read?

switch($row[’type’]) {
case ‘textfield’:
$formfield = ‘<tr><td class=”formbg1″><b>’.$row[’name’].’:</b></td><td class=”formbg2″><input type=”text” name=”customfields[’.$row[’id’].’]” maxlength=”‘.$row[’maxlength’].'” size=”‘.$row[’maxlength’].'” value=”‘.$value.'”></td></tr>’.”n”;

case ‘list’:
$formfield = ‘<tr><td class=”formbg1″><b>’.$row[’name’].’:</b></td><td class=”formbg2″><select name=”customfields[’.$row[’id’].’]”><option value=””>Select One</option>’.”n”;

foreach($values as $val) {
if ($value==$val) { $selected = ” selected”; } else { $selected =
“”; }
$formfield .= ‘<option value=”‘.$val.'”‘.$selected.’>’.$val.'</option>’.”n”;
$formfield .= ‘</select>’.$fields[’field1’].'</td></tr>’.”n”;

switch($row['type']) {
    case 'textfield':
$formfield = '<tr><td class="formbg1"><b>'.$row['name'].':</b></td> <td class="formbg2"><input type="text" name="customfields['.$row['id'].']" maxlength="'.$row['maxlength'].' " size="'.$row['maxlength'].'" value="'.$value.'"></td></tr>'."n";

case 'list': $values=explode(',',$row['values']); $formfield = '<tr><td class="formbg1"> <b>'.$row['name'].':</b></td><td class="formbg2"> <select name="customfields['.$row['id'].']"> <option value="">Select One</option>'."n";
foreach($values as $val) { if ($value==$val) { $selected = " selected"; } else { $selected = ""; } $formfield .= '<option value="'.$val.'"'.$selected.'>'.$val.' </option>'."n"; } $formfield .= '</select>'.$fields['field1'].'</td></tr>'."n";

Just as in HTML, indenting in PHP makes a script easier to follow. The general rule for indenting goes like this: all statements within control structures (if..else.., while, foreach, switch, and so forth) should be indented one unit. The typical “unit” consists of 4 spaces, though some people prefer to use a single tab or an alternate number of spaces.

Modularize Scripts

When the term modularization is used in the context of programming, it refers to the process of breaking a large application up into separate parts, or “modules,” that perform specific jobs. For example, if you were building an address book application, you might have one script that allowed users to view addresses, another to allow a new user to be added, another to handle edits, and a final one for deletions. This type of a modular coding is a first step—good programmers take it farther.

When you begin writing a script, you will find that certain blocks of code are frequently re-used. Common tasks like connecting to databases, validating user input, and checking a user’s login information can occur multiple times throughout the scripts of a complete application. Initially, the inclination might be to copy and paste your code block to wherever it happens to be needed. But, this gets messy; if you need to alter the code block in one script, you’re condemned to updating it everywhere else it occurs.

Here, modular programming moves to the next level.

Typically, programmers will create one or more shared files at the beginning of the programming process. In almost every case, there is a least one file (often called global.php or lib.php) that contains any functions or classes that are used multiple times throughout an application. In addition, there may be a separate file that is used to store configuration variables for the script. Often times, these are variables that would need to be changed if a script was being distributed or moved from server to server (such as directory names, or database login information, and so forth). By condensing them into a single, separate file, the process of updating them becomes significantly easier. It also eliminates the need to comb through individual script files to make changes.

These “global” files can be shared among all the other scripts in the application by including them using the include() or require() functions. Once they are included, any of the functions or variables within them can be used as though they were part of the running script itself.

Separate PHP and HTML

One of the highlights of the PHP scripting model is that code can be freely mixed with HTML. It is one of the reasons that writing scripts is so fast and easy, and it is one of the things has helped make PHP one of the most popular Web scripting languages.

However, there is a price to be paid for utilizing this flexibility.

Files with combined HTML and PHP quickly become bulky. Anyone charged with designing the user interface for a script (even if it is yourself) has to wade through lines of programming to change or add HTML. Without experience with PHP, this can be an insurmountable challenge. And, changing the front end of an application means editing the script itself, which can easily lead to broken code.

These are just some of the reasons that many developers use template classes such as Smarty and Fast Templates. These classes allow the complete separation of programming logic and design. All the design elements of a site are broken down and stored in separate template files. Only after the PHP script has executed all of the code to generate the page are the templates called and the output finally assembled and displayed.

The end goal is to have PHP files that contain no HTML, and HTML files that contain no PHP. This separation process can become very complex, especially for the novice programmer. But there are at least two things you can do to achieve some of the same result, even without using template engines:

  • If your site has the same header, footer, and/or navigation, put the HTML for these elements in separate files. You can include the files as needed by using the include() command, or with PHP’s read file functions. This allows you to update these areas site-wide, without directly editing any PHP.

  • Rather than outputting page content as you go, output it last. Assign all the dynamic content to variables, and then include these variables in the HTML for the page. This makes it easier to alter the layout of any pages later on.

Avoid Double Quotes Around Strings that Contain HTML

PHP offers a choice between using single or double quotes around strings (as well as perl’s “heredoc”). The difference between the two methods is that variables are expanded within double quotes, but not within single quotes.

To avoid variable concatenation, many people get in the habit of using double quotes for strings. But HTML also uses double quotes for attributes, and so lines of code can easily wind up looking like this:

$var = “<table width=”0″ border=”0″ cellpadding=”0″
width=”100%” cellspacing=”0″><tr><td style=”font-family:Verdana;”><a

Strings like this should be re-written as:

= ‘<table width=”0″ border=”0″ cellpadding=”0″
width=”100%” cellspacing=”0″><tr><td style=”font-family:Verdana;”><a

By using single quotes, the need to escape every interior double quote is removed. There is a very small performance gain that can add up over the course of a single script (especially in cases where there are no variables within the string), because the processor does not need to search the string for any variables.

Use Logical and Consistent Naming Conventions

As much comic relief as it might provide to name all your functions after the Seven Dwarves or your variables after countries, four months down the line, you won’t have much luck figuring out what doc($canada); was supposed to do.

Names for elements should be short, but descriptive of the task they perform or the information they hold. If you decide to capitalize function names, maintain the same format for all of them.


It is hard to discuss coding style without devoting a few paragraphs to mention PEAR. “PEAR” is an acronym for the PHP Extension and Add-on Repository. One of the organization’s goals is to amass a large collection of open source code for PHP developers to use within their own projects. Because this is a collaborate effort of massive scale, a secondary goal is to define a standard for PHP coding style. This ensures consistency within their own archives, and encourages it throughout the entire PHP community.

PEAR’s guidelines go beyond general suggestions of “best practices” to establish specific and detailed rules. For example, PEAR shares the common idea that code should be indented. But they also expand on it, specifying that 4 spaces should be used for indents, and “tab” should never be used.

Is it worth bringing your code in line with PEAR? Well, probably so, unless there is some aspect you particularly abhor or are uncomfortable with. Many of these rules are adopted from C and fall in line with style guidelines from other programming languages. Though strict, they are generally easy to implement.

(PEAR’s complete documentation on coding standards can be found at:


Hopefully, this article has given you a little bit of insight into methods of organizing and writing your scripts so that they are more easily maintained and upgraded. Many of the concepts introduced here rely on common sense; others are learned and eventually become second nature as you continue to write more scripts.

Next time, we’ll be delving into the topic of MySQL and PHP with the first of a four-part series. Stay tuned!

Liz Fulghum currently lives in Annapolis, MD where she works as a web designer for a custom shirt retailer. Liz was convinced to try PHP as an alternative to Perl; she has been a fan ever since and frequently works as a freelance developer.

# # #

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories