Top 15+ Best Practices for Writing Super Readable Code
Tutorial Details
- Topic: PHP Best Practices
- Difficulty: Intermediate
Twice a month, we revisit some of our readers’ favorite posts from throughout the history of Nettuts+.
Code readability is a universal subject in the world of computer programming. It’s one of the first things we learn as developers. This article will detail the fifteen most important best practices when writing readable code.
1 - Commenting & Documentation
IDE’s (Integrated Development Environment) have come a long way in the past few years. This made commenting your code more useful than ever. Following certain standards in your comments allows IDE’s and other tools to utilize them in different ways.
Consider this example:

The comments I added at the function definition can be previewed whenever I use that function, even from other files.
Here is another example where I call a function from a third party library:

In these particular examples, the type of commenting (or documentation) used is based on PHPDoc, and the IDE is Aptana.
2 - Consistent Indentation
I assume you already know that you should indent your code. However, it’s also worth noting that it is a good idea to keep your indentation style consistent.
There are more than one way of indenting code.
Style 1:
function foo() {
if ($maybe) {
do_it_now();
again();
} else {
abort_mission();
}
finalize();
}
Style 2:
function foo()
{
if ($maybe)
{
do_it_now();
again();
}
else
{
abort_mission();
}
finalize();
}
Style 3:
function foo()
{ if ($maybe)
{ do_it_now();
again();
}
else
{ abort_mission();
}
finalize();
}
I used to code in style #2 but recently switched to #1. But that is only a matter of preference. There is no “best” style that everyone should be following. Actually, the best style, is a consistent style. If you are part of a team or if you are contributing code to a project, you should follow the existing style that is being used in that project.
The indentation styles are not always completely distinct from one another. Sometimes, they mix different rules. For example, in PEAR Coding Standards, the opening bracket "{" goes on the same line as control structures, but they go to the next line after function definitions.
PEAR Style:
function foo()
{ // placed on the next line
if ($maybe) { // placed on the same line
do_it_now();
again();
} else {
abort_mission();
}
finalize();
}
Also note that they are using four spaces instead of tabs for indentations.
Here is a Wikipedia article with samples of different indent styles.
3 - Avoid Obvious Comments
Commenting your code is fantastic; however, it can be overdone or just be plain redundant. Take this example:
// get the country code
$country_code = get_country_code($_SERVER['REMOTE_ADDR']);
// if country code is US
if ($country_code == 'US') {
// display the form input for state
echo form_input_state();
}
When the text is that obvious, it’s really not productive to repeat it within comments.
If you must comment on that code, you can simply combine it to a single line instead:
// display state selection for US users
$country_code = get_country_code($_SERVER['REMOTE_ADDR']);
if ($country_code == 'US') {
echo form_input_state();
}
4 - Code Grouping
More often than not, certain tasks require a few lines of code. It is a good idea to keep these tasks within separate blocks of code, with some spaces between them.
Here is a simplified example:
// get list of forums
$forums = array();
$r = mysql_query("SELECT id, name, description FROM forums");
while ($d = mysql_fetch_assoc($r)) {
$forums []= $d;
}
// load the templates
load_template('header');
load_template('forum_list',$forums);
load_template('footer');
Adding a comment at the beginning of each block of code also emphasizes the visual separation.
5 - Consistent Naming Scheme
PHP itself is sometimes guilty of not following consistent naming schemes:
- strpos() vs. str_split()
- imagetypes() vs. image_type_to_extension()
First of all, the names should have word boundaries. There are two popular options:
- camelCase: First letter of each word is capitalized, except the first word.
- underscores: Underscores between words, like: mysql_real_escape_string().
Having different options creates a situation similar to the indent styles, as I mentioned earlier. If an existing project follows a certain convention, you should go with that. Also, some language platforms tend to use a certain naming scheme. For instance, in Java, most code uses camelCase names, while in PHP, the majority of uses underscores.
These can also be mixed. Some developers prefer to use underscores for procedural functions, and class names, but use camelCase for class method names:
class Foo_Bar {
public function someDummyMethod() {
}
}
function procedural_function_name() {
}
So again, there is no obvious “best” style. Just being consistent.
6 - DRY Principle
DRY stands for Don’t Repeat Yourself. Also known as DIE: Duplication is Evil.
The principle states:
“Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.”
The purpose for most applications (or computers in general) is to automate repetitive tasks. This principle should be maintained in all code, even web applications. The same piece of code should not be repeated over and over again.
For example, most web applications consist of many pages. It’s highly likely that these pages will contain common elements. Headers and footers are usually best candidates for this. It’s not a good idea to keep copy pasting these headers and footers into every page. Here is Jeffrey Way explaining how to create templates in CodeIgniter.
$this->load->view('includes/header');
$this->load->view($main_content);
$this->load->view('includes/footer');
7 - Avoid Deep Nesting
Too many levels of nesting can make code harder to read and follow.
function do_stuff() {
// ...
if (is_writable($folder)) {
if ($fp = fopen($file_path,'w')) {
if ($stuff = get_some_stuff()) {
if (fwrite($fp,$stuff)) {
// ...
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
For the sake of readability, it is usually possible to make changes to your code to reduce the level of nesting:
function do_stuff() {
// ...
if (!is_writable($folder)) {
return false;
}
if (!$fp = fopen($file_path,'w')) {
return false;
}
if (!$stuff = get_some_stuff()) {
return false;
}
if (fwrite($fp,$stuff)) {
// ...
} else {
return false;
}
}
8 - Limit Line Length
Our eyes are more comfortable when reading tall and narrow columns of text. This is precisely the reason why newspaper articles look like this:

It is a good practice to avoid writing horizontally long lines of code.
// bad
$my_email->set_from('test@email.com')->add_to('programming@gmail.com')->set_subject('Methods Chained')->set_body('Some long message')->send();
// good
$my_email
->set_from('test@email.com')
->add_to('programming@gmail.com')
->set_subject('Methods Chained')
->set_body('Some long message')
->send();
// bad
$query = "SELECT id, username, first_name, last_name, status FROM users LEFT JOIN user_posts USING(users.id, user_posts.user_id) WHERE post_id = '123'";
// good
$query = "SELECT id, username, first_name, last_name, status
FROM users
LEFT JOIN user_posts USING(users.id, user_posts.user_id)
WHERE post_id = '123'";
Also, if anyone intends to read the code from a terminal window, such as Vim users, it is a good idea to to limit the line length to around 80 characters.
9 - File and Folder Organization
Technically, you could write an entire application code within a single file. But that would prove to be a nightmare to read and maintain.
During my first programming projects, I knew about the idea of creating “include files.” However, I was not yet even remotely organized. I created an “inc” folder, with two files in it: db.php and functions.php. As the applications grew, the functions file also became huge and unmaintainable.
One of the best approaches is to either use a framework, or imitate their folder structure. Here is what CodeIgniter looks like:

10 - Consistent Temporary Names
Normally, the variables should be descriptive and contain one or more words. But, this doesn’t necessarily apply to temporary variables. They can be as short as a single character.
It is a good practice to use consistent names for your temporary variables that have the same kind of role. Here are a few examples that I tend use in my code:
// $i for loop counters
for ($i = 0; $i < 100; $i++) {
// $j for the nested loop counters
for ($j = 0; $j < 100; $j++) {
}
}
// $ret for return variables
function foo() {
$ret['bar'] = get_bar();
$ret['stuff'] = get_stuff();
return $ret;
}
// $k and $v in foreach
foreach ($some_array as $k => $v) {
}
// $q, $r and $d for mysql
$q = "SELECT * FROM table";
$r = mysql_query($q);
while ($d = mysql_fetch_assocr($r)) {
}
// $fp for file pointers
$fp = fopen('file.txt','w');
11 - Capitalize SQL Special Words
Database interaction is a big part of most web applications. If you are writing raw SQL queries, it is a good idea to keep them readable as well.
Even though SQL special words and function names are case insensitive, it is common practice to capitalize them to distinguish them from your table and column names.
SELECT id, username FROM user; UPDATE user SET last_login = NOW() WHERE id = '123' SELECT id, username FROM user u LEFT JOIN user_address ua ON(u.id = ua.user_id) WHERE ua.state = 'NY' GROUP BY u.id ORDER BY u.username LIMIT 0,20
12 - Separation of Code and Data
This is another principle that applies to almost all programming languages in all environments. In the case of web development, the “data” usually implies HTML output.
When PHP was first released many years ago, it was primarily seen as a template engine. It was common to have big HTML files with a few lines of PHP code in between. However, things have changed over the years and websites became more and more dynamic and functional. The code is now a huge part of web applications, and it is no longer a good practice to combine it with the HTML.
You can either apply the principle to your application by yourself, or you can use a third party tool (template engines, frameworks or CMS’s) and follow their conventions.
Popular PHP Frameworks:
Popular Template Engines:
Popular Content Management Systems
13 - Alternate Syntax Inside Templates
You may choose not to use a fancy template engine, and instead go with plain inline PHP in your template files. This does not necessarily violate the “Separation of Code and Data,” as long as the inline code is directly related to the output, and is readable. In this case you should consider using the alternate syntax for control structures.
Here is an example:
<div class="user_controls">
<?php if ($user = Current_User::user()): ?>
Hello, <em><?php echo $user->username; ?></em> <br/>
<?php echo anchor('logout', 'Logout'); ?>
<?php else: ?>
<?php echo anchor('login','Login'); ?> |
<?php echo anchor('signup', 'Register'); ?>
<?php endif; ?>
</div>
<h1>My Message Board</h1>
<?php foreach($categories as $category): ?>
<div class="category">
<h2><?php echo $category->title; ?></h2>
<?php foreach($category->Forums as $forum): ?>
<div class="forum">
<h3>
<?php echo anchor('forums/'.$forum->id, $forum->title) ?>
(<?php echo $forum->Threads->count(); ?> threads)
</h3>
<div class="description">
<?php echo $forum->description; ?>
</div>
</div>
<?php endforeach; ?>
</div>
<?php endforeach; ?>
This lets you avoid lots of curly braces. Also, the code looks and feels similar to the way HTML is structured and indented.
14 - Object Oriented vs. Procedural
Object oriented programming can help you create well structured code. But that does not mean you need to abandon procedural programming completely. Actually creating a mix of both styles can be good.
Objects should be used for representing data, usually residing in a database.
class User {
public $username;
public $first_name;
public $last_name;
public $email;
public function __construct() {
// ...
}
public function create() {
// ...
}
public function save() {
// ...
}
public function delete() {
// ...
}
}
Procedural functions may be used for specific tasks that can be performed independently.
function capitalize($string) {
$ret = strtoupper($string[0]);
$ret .= strtolower(substr($string,1));
return $ret;
}
Object-Oriented Programming in PHP
Take your skills to the next level with this Premium video course.
15 - Read Open Source Code
Open Source projects are built with the input of many developers. These projects need to maintain a high level of code readability so that the team can work together as efficiently as possible. Therefore, it is a good idea to browse through the source code of these projects to observe what these developers are doing.

16 - Code Refactoring
When you “refactor,” you make changes to the code without changing any of its functionality. You can think of it like a “clean up,” for the sake of improving readability and quality.
This doesn’t include bug fixes or the addition of any new functionality. You might refactor code that you have written the day before, while it’s still fresh in your head, so that it is more readable and reusable when you may potentially look at it two months from now. As the motto says: “refactor early, refactor often.”
You may apply any of the “best practices” of code readability during the refactoring process.
I hope you enjoyed this article! Any that I missed? Let me know via the comments.


Hey, finally a tutorial on here that advocates an intelligent mix of OOP and Procedural. Tired of the extremists ranting that one way or the other is the omega.
Good read.
I think points 1 and 3 can be better tackled by using the Extract to Method refactoring technique (http://blog.objectmentor.com/articles/2009/09/11/one-thing-extract-till-you-drop)
If you find the need to comment code then it isn’t readable enough. Wrap it in a method that describes what it does.
Good tutorial. It’s pretty much what I tell everybody.
Maybe one thing is missing: I’m a fanatic believer in DRY (you mentioned that) and KISS.
Keep it simple, stupid! Avoid unneccessary complexity, work hard to make your code as simple as possible. Don’t try to “show off”!
Exactly.
Sometimes you can show off by trying to simplify things as well. For example, the ternary operator can make a simple if-check even simpler. But used inappropriately, it can really just confuse the reader!
I disagree about uppercase SQL keywords. Lowercase is perfectly readable. The rest are great tips.
I think its a good practice so if you read any SQL code you can clearly identify whats SQL statements/functions and what are the variables/columns/tablse/etc:
SELECT id FROM users WHERE id = 1;
- vs -
SELECT ID FROM USER WHERE I D= 1;
select id from user where id = 1;
I think first is just better and easier to read IMHO, but well an ORM is just better than both.
Great tut! I have to say one of the most annoying things is having to go back behind someone to fix a problem, and find that their code is NOT documented cleanly. It really does make a difference. Thanks for the reminder! :-)
I think one thing that is a MUST for every CodeIgniter developer (and could be also good for any PHP developer) is to read the CodeIgniter Style Guide:
http://codeigniter.com/user_guide/general/styleguide.html
It states the following: “The following page describes the coding rules use adhere to when developing CodeIgniter.”
It’s great so your code will be extremely clean and easier to read.
Another good practices are:
1) Try Python or any other coding languange: Make you a better coder. Also, in Python the tabs are mandatory (if you don’t indent your code, it won’t work).
2) Use some coding and arquitectural patterns (like MVC).
3) Plan before you write any code :P
Great article btw!
Perfect article. One of the best. I’m going to look up on better commenting techniques, because right now I know not clue what I should comment, what I shouldn’t, wether I should use a single line here, or multiple lines….
Nice tut,
most points are really important – every beginner should read such a tut before just starting to write something.
Very helpful! Thank you!
Awesome as always. Very useful collection of tips.
Thanks
Bookmarked! Very usefull .. Thank you a lot dude ;-)
Nice post. All so true! :)
thx so much… this is very useful! ^^
Just wanted to add that often times Class names with underscores are used as some kind of crude namespace feature. Have a look at Zend Framework and the folder hierarchy to see what I mean. The advantage of this conventions is fever class name clashes and good autocompletion in IDEs. The disadvantage is Very_Long_Classnames. But IDE autocompletion and PHP 5.3 Namespaces will take care of that.
I wish everyone would follow these tips. Btw, I use indentation style #2 and noticed that most people don’t so it might be time to do make the switch.
Nice Post Burak. Especially, I liked #1 & #2
thx for sharing! :)
hi from russia :)
I don’t agree with #4. Whenever I see blocks of code with (some?) spaces between them I think that separate functions would have been a better choice:
[...]
$forums = getListOfForums();
loadTemplates($forums)
[...]
function getListOfForums() {
$forums = array();
$r = mysql_query(“SELECT id, name, description FROM forums”);
while ($d = mysql_fetch_assoc($r)) {
$forums []= $d;
}
return $forums;
}
function loadTemplates($forums) {
load_template(‘header’);
load_template(‘forum_list’,$forums);
load_template(‘footer’);
}
[...]
Reusable code. No superfluous spaces. And – yes I’m one of those who loves self-describing code.
I hope you think more carefully about your coding than what you just said here, because there are dozens of examples where it would be very unwise to factor a code block into its own function, but where it’s distinct from other parts.
Example (in Perl; the same ideas apply to any other language, though):
sub foo {
my %args = shift;
$tmpfile = ‘/tmp/’.$args{pid};
open(my $fh = IO::File->new, “>+”, $tmpfile) or die “error”;
flock($fh, LOCK_EX);
do_something();
write_results_to($tmpfile);
post_process($tmpfile);
local $/ = undef;
my $result = ;
flock($fh, LOCK_UN);
unlink $tmpfile;
return \$result;
}
This is a contrived and trivial example, but it demonstrates my point; just because different parts of a function can be grouped together into sections (“initialization”, “processing”, “cleanup”, e.g.) doesn’t mean it makes the least bit of sense to break those sections away into their own function, and, in fact, it can be flat-out impossible to do.
Whoops, guess the commenting system removed a couple items enclosed in angle brackets; also, it should be %args = @_, not shift.
Wonderful tutorial, Thanks for sharing
Simple to understand. Why is it so hard to applicate :D
discovered CodeIgniter recently, love it ! Why make it complicated ?
I do so many of these, and thanks to great advice like this!
Good work
Glad to see that I’m using most of these practice, I’ll do the one I don’t next.
Thank you for this !
I THINK THIS WAS COMMON SENSE BECAUSE EVERYONE SHOULD ALWAYS USE THIS WAY OF CODING FROM THE BEGINNING, LIKE THEY MIGHT HAVE OTHER CODE SIMULAR, BUT ACCURATELY UNIQUE.
Thanks for sharing your experiences in coding, I’ll follow them in my following projects.~
#2. I also do this as well:
// Ternary Operator
$var = isset($var)
? ‘foo’
: ‘bar’;
// SQL:
SELECT
a.column,
b.column
FROM table as a,
JOIN table as b
ON b.column = a.column
WHERE a.column = ‘foo’
AND b.column = ‘bar’
ORDER BY a.column
// Arrays
$arr = array(
‘foo’ => ‘bar’,
array(
‘abc’ => 123
)
);
Alot of people forget the importance of readable code. Thank you for reminding me with these great tips
teşekürler..
I agree with everything but some of #10.
I cannot stand for the life of me one letter variables anywhere but a counter in my for loop.
I have the same thoughts, although I can also survive them in simple (ie get/set) methods, where there’s no chance of confusion eg:
public void setName(String n)
{
this.name = sanitise(n);
}
In this situation I think n is pretty clear, while name would cause conflicts with the instance variable name, and newName/myName is simply un-necessary. Horses for courses and all that, though.
Great article.
Excellent article and some great common sense points that everyone should adhere too.
I like the part the author mentions don’t use obvious comments, I am guilty of that at times.
A note is that this article applies to all code not just codeignitor
Regarding commenting, which seems to be an issue of debate here, I heard/read a great thought on it once.
“The code should explain what you are doing, and the comments explain why you are doing it”
ie your naming of methods, functions, constants and variables should allow a competant programmer to understand what is going on, pretty much instantly. Comments should be used to explain why you are doing something in a block of code, particularly if that operation is in some way out of the ordinary.
eg if I see (assume pseudo-ish Java, not that anyone would ever do this)
public String getNameByID (int id)
{
return studentName[id];
}
I can pretty clearly see that there’s an array of studentNames, and they’re getting the name by the ID, which doubles up as the index of the array.
It’s only if they start doing funny things with hashing functions that they may want to explain what on earth they think they’re doing
public String getNameByID (int id)
{
//superSecretHashing thing to stop people stealing our data from the array!
id = (id+5) % 11
return studentName[id];
}
One of the few code style guides I’ve seen that doesn’t suck. Nicely done.
Kohana should be listed as a premier PHP framework.
Great article . It helps me a lot in coding web :)
Thanks for Great Information~~~
Excellent points, especially for us codeigniter fans
Well done as usual Burak
Great tutorial!
Great Blog
Good comments but the most obvious thing of all would be to cease to use legacy languages like PHP and get on board with a modern language such as Ruby on Rails. PHP (Python and Perl are no better) is a bit like the devils tool – very easy to write atrocious code. Honestly how often do you see the word “class” in a typical php file?
“Ruby on Rails” is not just a language, it includes a framework. That’s like saying PHP+CodeIgniter or PHP+Zend Framework. If you look at the source of code of PHP applications built with such frameworks, you will see the word “class” plenty of times, if that is how you determine a language to be “modern”.
Your comment makes it very clear that you don’t really have much experience writing large applications. You can write crappy code in any language. You can write crappy code that looks professionally done in any language if you’re using a framework like Rails or Zend. The number of times the word “class” (or any other keyword) is used in a file means nothing. In fact, my personal best practice is to never define more than one class in a given php file, so the number of times you’ll see the word class in my php files is <= 1.
What's more important is to use good object oriented principles in developing your application like favoring composition over inheritance, coding to an interface instead of an implementation, and abstracting out the principle that varies. The principles of good object oriented design are the same no matter what language you're using.
A lot of people using PHP don’t even know what a class is, do keep that in mind.
Nice guide, I definitely enjoyed it.
Popular Content Management Systems, I didn’t see a list of them in the article, why are they missing?
Also, do you guys feel like it’s cheating to use a PHP framework? I question whether I should get into one. xD
As always style guidelines are VERY controversial :)
There are many guidelines which are universally applicable, others are not; since your examples are all in PHP this article would’ve better be called “Code guidelines for PHP programmers” :)
If there’s 1 thing I could say for sure about code guidelines is that PHP is the worst language from that point of view :) I’m using it for almost 10 years now and I’ve seen a huge amount of functions doing almost the same thing but called in a slightly different way being added to PHP over the years …
in the end you have over lengthy word by underscore separation functions like mysql_escape_string, mysql_real_escape_string …
then you have 1 word all lowercaps – “floatval” for example and “sizeof” …
then you have unreadable/unpronounceable “strcspn” – who know what that one does without checking the docs ?
then you have all caps constants : __FUNCTION__
and CamelCase class names …
and in the end you have the new and shiny just added GOTO operator which use is officially banned from the programmers world :)
Well .. PHP is what it is – the most popular web language out there :)
if you are using php framework like codeigniter or cakephp (i haven’t exploring other framework) there are coding standar that recommended, they avaliable in the framework documentation
Good read.
About the newspaper columns: they actually look like that because they need to cram as much text as possible in paper. Optimal width for reading is around 8 words per line.
Awesome info.. read the first one and then found myself reading through the whole thing! This post is great though because the more people who read this, the better off the web is ;)
Maybe I can add one more – avoid magic numbers. The solution is simple, define your constants, or at least use variables.
Just in case if somebody is wondering, magic numbers is unnamed numerical constant (http://en.wikipedia.org/wiki/Magic_number_%28programming%29#Unnamed_numerical_constants)
It’s when you simply use numbers like 60, 43 or anything else in your programming. When you do this, you (later) or other programmers may wonder what those numbers are for. For example
for ($i = 0; $i < 52; $i++) { … }
one may wonder what 52 is… but it's a lot clearer when you do this
for ($i = 0; $i < WEEKS_IN_YEAR; $i++) { … }
Very good point!
Excellent point!
Please add this to the article.
Great.. work..thanks for sharing..
Great, if only we could get all of the PHP coders in the world to read this and abide by its principles. If PHP doesn’t adopt some sense of style or standards, the language will only get worse.
I love all practices for improving the code. You can always learn a few things.
Really useful and it’s a shame most of coders out there won`t care about this..
PHP makes me LOL
Anyone interested in going deeper should read Code Complete.
Good idea to fart less in the mouth of a coder.
Always good to get a few tips on better coding practices. Nice one!