PHP Best Practices For Beginners

cli

In PHP, and really in just about every programming language in existence, there are certain things that are important to remember. Some of them are very general and can be applied to almost all programming languages, while others are best associated with one specific programming language.

In this post you will find nine PHP best practices that everyone really should follow.

You can also take a look at a couple of other "best practices" articles, previously from FWebDe:

Avoid Using Short Tags

We all know what they look like. Various forms of PHP short tags exist, such as <? ?> and
<?= ?>. These should be avoid at all costs, for multiple reasons.

The first reason is that they can get in the way of certain XML parsers, potentially causing a whole bunch of problems. The second reason is that they can be disabled in certain server configurations, making your code less portable.

Be As Strict As Possible

In other words, don't let the PHP interpreter pick up the slack for you. It is always best to try to be as strict as possible. Certain things may not cause errors, but they are generally bad coding practices. Here is an example:

<?php
$foo = array();
$foo[bar] = 3;
?>

Can you spot the problem in this example?

The array index is not surrounded with quotes ($foo[bar]). When executed, this may not raise any errors, but it is a bad programming practice, as array indices in PHP are supposed to be surrounded in quotation marks.

Another example of not being strict enough would be using PHP short tags, as above.

Comment Your Code

Make sure that you leave some comments inside of your source code, to help explain certain parts that might be a bit more difficult to understand just from looking at the code itself. This will also help out a lot when you have to go back and maintain a project from a long time ago, so that you will know what is going on.

That said, do not go and add a comment to every line. There is a point where too many comments negatively impacts your code's readability. As a general rule, if you start to have more lines of comments than actual code, you're doing it wrong.

Keep Loops As Simple As Possible

This is a very important thing to remember. By keeping your loops as simple as possible, you can greatly speed up the execution of your program. Here is an example of what not to do:

while ($c == $someValue) {
    $a = hugeFunction(); // Note: does not change with each iteration
    echo $c + $a;
}

Assuming that the result of hugeFunction() stays the same every time, and takes a long time to execute, it can have a huge impact on performance. In this example, hugeFunction() is called at every iteration of the loop, increasing the amount of time it takes each time. Here is a much better example:

$a = hugeFunction();
 
while ($c == $someValue) {
    echo $c + $a;
    // blah
}

Setup Your Own Testing Server

You can really develop much more quickly if you have your own testing server setup, so that you don't have to worry about uploading your files to a server after each change. I also feel that having my own testing server setup on my own computer is much easier than editing files remotely.

This is made easy with XAMPP. It is a cross-platform distribution of Apache, including MySQL, PHP, Perl and various tools such as phpMyAdmin. Setup is very easy, download the distribution and extract it. From there, just move your files into the appropriate directory and you're ready to go!

Improve Your Code Readability

When you first start out writing programs, you're probably going to be spending almost all of the time typing out the actual code, not worrying about readability, just typing it out in a way that comes to you as you go along. Take this for example:

<?php
function echoStuff() { echo 'stuff'; echo 'not really! haha'; }   if(1==1) {
echoStuff(); $a = 3;
 echo $a;
}
else {$a = 5; echo $a; echoStuff(); echo 'foo';} ?>

Not only is this completely unreadable, but it is inconsistently unreadable. Certain things are indented differently, and certain lines contain many statements while others contain only one. Probably the most important part of code readability is consistency. Pick a certain style and stick to it.

If you could read that example above just perfectly, you may want to consider seeking professional help.

For more detailed tips on improving code readability, check out Tips to Improve Your Code Readability Today.

Of course if you want to go out of your way to torture others, check out a different article: How to Write Completely Unreadable Code.

Prefer Single Quoted Strings When Possible

$a = 'asdf';
$b = "asdf';

There may not be much of a difference, right? Well, the difference may be small, but you should generally give preference to single quoted strings as much as possible. In PHP, double quoted strings are searched through for variables, which can waste time if done unnecessarily. Here is a better way to insert variables into strings:

$a = 'asdf';
$b = 'asdf ' . $a . ' asdf'; // asdf asdf asdf

However if you are using echo, there is an even faster way:

echo 'asdf ', $a, ' asdf';

An uncommon way of using echo is to use it more like a function. When using the string concatenation operator (.), the entire string is added together, and then output. This other way, however, is faster because no string operations are performed, one parameter is simply output after another.

Try a Framework

Once you have learned the basics of PHP and can get the hang of creating simple applications, you may want to try out a PHP framework. There are many different PHP frameworks that include tons of different tools to help create applications much more quickly, such as database classes, various helpers, and more.

Not sure which framework to choose? There are many options to choose from, some of which are outlined in this list of popular web development frameworks.

Personally, my favourite PHP framework is CodeIgniter. It is fast and lightweight, and very easy to setup for beginners. To get started with CodeIgniter, check out an Introduction to CodeIgniter.

But make sure that you at least know the basics of PHP before diving into the framework. It is important to first understand how the PHP code itself works.

Use the PHP Manual

The PHP Manual is pretty much the official guide to PHP. Here you will find excellent documentation for just about every aspect of the language, from a guide to the syntax, to the function reference.

When you search Google for information about a specific PHP function, you will most likely get a page in the PHP function reference as the first result. For each function included, you will find a description of the function and what it does, how the function should be used, and usually a helpful example.

Do you follow these PHP best practices? Do you have any others that you would like to share? Be sure to leave a comment.

Stay Updated

Did you enjoy this post? Don't miss a single post by getting free updates!

12 Comments

  1. April 14, 2010

    Great article Eric.
    Especially important for people just starting out in PHP

  2. April 14, 2010

    I think your best suggestion is "try a framework".

  3. mario
    April 14, 2010

    "Prefer Single Quoted Strings When Possible"
    Repeating silly assumptions over and over doesn't make them true.
    The PHP parser (and tokenizer!) have been optimized quite sime time ago. There is no factual speed advantage in using single quotes, in many cases double quotes are actually faster. This has been posted all over the tubes. Read up.

    And then, speed difference in string quotation should be the least of your worries. If you are string concating database queries and not using parameterized SQL, this *SLIGHTLY* outweights anything else speed-wise. (Let's not get started about security even.)
    So panicking about coding style and quotation method is not appropriate if you don't even master the basics.

  4. Jeremy
    April 15, 2010

    Short tags are great for a lot of things especially improving code readability. When you have a large chunk of html with sporadic variables placed it is much easier to read more than .

    Php isn't a strict language. You're asking people to slow down their scripts with superfluous code. This isn't C, unless you're using OOP you don't need to declare your variables.
    2 assignments
    $foo = array();
    $foo['bar'] = "";

    1 assignment
    $foo['bar'] = "";

    I like a lot of your other suggestions though.

    • April 15, 2010

      Did I say that? I guess I may not have been completely clear with that. I was saying that you should remember to use quotes around the index.

      But that is a good point to remember :)

  5. April 15, 2010

    echo 'asdf ', $a, ' asdf';
    Using commas instead of creating a new string.
    Well, you learn something new every day. Thanks.

  6. Cany000n
    April 16, 2010
    $a = hugeFunction();
     
    while ($c === $someValue) {
        echo $c + $a;
        // blah
    }

    Better, no? Also little bit faster. ;)

    • April 16, 2010

      That's probably a bit better. And it is, unfortunately, something that I forget to use all the time!

  7. Cany000n
    April 16, 2010

    @eric
    i was just joking, It was in rapport being strictly as possible, in fact, not like my english is ;) Bookmarked. ++

  8. June 1, 2010

    Hello Eric, I'm a php beginner and this article is right for me :) I'm in the proces of creating my first simple app, so thanks for the tips, really appreciated.
    Will try Codeigniter in few months as you suggest.

Trackbacks/Pingbacks