20 Tips you need to learn to become a better PHP Programmer

PHP is a very versatile programming language that can achieve the same objective in multiple ways. You can read more about that in my ‘The Art of Programming‘ post. Below are a few tips I’ve picked up from past projects that can improve your code readability and maintainability and make you a neater, more organized PHP programmer.

Here you go:

Use <?php and ?>

To start your script, avoid using <? ?>. While these may work on your server, they might not work on another server if you ever decide to run your script elsewhere.

Similarly, when echoing a variable, try to avoid using the shortcut tags as they might not be supported everywhere. I found it pretty hard to stop using them since they save so much space but at the end of day, they do make your code more portable.

<? ... ?> // Incorrect
<?php ... ?> // Correct

<?=$Var?> // Incorrect
<?php echo $Var ?> // Correct

Separate Configuration Files

There’s no reason you should be adding configuration settings to your script file. Always create a separate file and include that file at the top of your script. The last thing you want is to have to edit each and every page because of a little configuration change. Including a file is super easy:


// code goes here ...

Comments are your Friend

Yep, I bet you saw this one coming? It’s amazing how hard we find it to understand our own code that has been written a while ago. Comments will help you figure out certain things which seemed obvious at the time. Here’s the syntax:

// Line One Comment
// Line Two Comment

/** Paragraph Comment
Paragraph Comment
Paragraph Comment **/

Easy, huh?

Use Indentation and Spacing

There’s nothing much worse than having to modify somebody’s code and realizing nothing has been indented properly. Having well indented code with the right spacing immediately says a lot about you as a programmer. Ideally, you should be able to immediately figure out whether a loop has ended or not by just quickly looking through your code. Here’s an example of badly indented code:

function  dothisformula($a,$b) { $c = $b+$a;
while ($c < 20) {
$e = $e - 1; $c = $c + 1; }
     return $e; }

And here’s the same code, properly formatted:

function dothisformula($a, $b) {
     $c = $b + $a;
     $e = 3;
     while ($c < 20) {
          $e = $e - 1;
          $c = $c + 1;
     return $e;

See what a difference some spacing makes?

Give your Variables Meaningful Names

Always give your variables name that mean something to you. Take this one step further by also including some details about what type of data they store. For instance, if we were using a variable as an integer, you could add an i to the beginning of the name. This especially important since we do not specify a type when declaring a variable in PHP.

Choosing whether to have caps or not in your variable name is up to you but it is often recommended to capitalize the first letter of every word in your variable. This makes it easy to read and understand.

Here’s what I use:

$iNumber = 10; // For Integers

$sName = "Marc"; // For Strings

$fPi = 3.14159265; // For Floats

$aNames = array(); // For Arrays

$oUser = new User(); // For Objects

$bIsMember = false; // For Booleans

Initialize your Variables

Although PHP will automatically create a variable the moment you try to assign a value to it, it is always good practice to initialize your variables before using them. This will make your code much cleaner and make sure your variables are always the type you want them to be:

$aArray = array();
$iInteger = 0;
$bBoolean = false;

Boolean is False, unless True

If you’re checking whether something is a specific value and storing the result in a boolean value, always start off assuming it’s false. For instance, the following code should be avoided:

function getStatus() {
    $bReturn = true;
    if ($i != 2) $bReturn = false;
    return $bReturn;

Instead, you should use:

function getStatus() {
    $bReturn = false;
    if ($i == 2) $bReturn = true;
    return $bReturn;

The second is the ideal solution for when you’re just checking one item. Why? Well, imagine you’re validating some data for a database – If, for whatever reason, your if statement is completely missed, your return value will still be false, therefore avoiding the input of invalid data. Since we frequently deal with sensitive data in PHP scripts, it’s better assuming something should not run until proven otherwise, rather than the other way round. I learned this the hard way.

Ideally, your validation should check what your data should be like, not what it shouldn’t be like.

Using Quotes when accessing Array Keys

When accessing arrays, you might find that the following two lines both work:

$sName = $aNames['marc'];
$sName = $aNames[marc];

In the second line, PHP is actually first trying to find a constant called “marc” and then converting “marc” to a string once no constant is found. Even though it works, you should avoid using no quotes as if you ever create a constant with the same name, your script would stop working.

Use commas to echo different strings

If you want to output both text and variables in the same string, you can use commas instead of dots. Why? Because it is marginally faster (based on this test).

echo "Hello, my name is ", $sName;

Instead of…

echo "Hello, my name is " . $sName;

Use Ternary Operators

If you have a simple IF statement, you can use a ternary operator which allows you to do the same thing in one line. Here’s an IF statement:

if ($a == 1) $b = 2;
else $b = 3;

You can do the same thing using a ternary operator as shown below:

$b = ($a == 1) ? 2 : 3;

Easy, right? The ternary operation is basically doing this:


Use === for Boolean Checks

If you’re checking whether a variable is true or false, use === rather than the usual == which we use for comparisons. The three equal signs tell PHP to also check the variable type.

if ($bIsMember == true) { ... } // Incorrect
if ($bIsMember === true) { ... } // Correct

Use ++ and — Operators

If you want to increase or decrease an integer by 1, you can easily use incrementing and decrementing operators. If you have the following code:

$iNumber = $iNumber  + 1;
$iNumber2 = $iNumber2 - 1;

This should be converted to:


The great thing about these operators is the way you can use them while completing other actions (for instance, in an if or while statement). Depending on whether you put the or ++ before the variable or after, the operator will run before or after the action is complete. The examples below are all valid uses and will help you understand what I mean:

$iNumber = 10;
while ($iNumber++ == 10) { ... }
// This will run once as the increment operator
// is run after the comparison

$iNumber = 10;
if (--$iNumber == 10) { ... }
// This will not run as the decrement operator
// is run before the comparison

$iNumber = 10;
$iTotal = $iNumber++;
// $iTotal will be 10. 

$iNumber = 10;
$iTotal = --$iNumber;
// $iTotal will be 9.

Use Assignment Operators

If you wanted to increase or decrease a variable by more than one, you can easily use assignment operators. Here’s how your code might look:

$a = $a + $b;
$a = $a * 5;
$a = $a - $d;
$a = $a / 3;

Using assignment operators, you can instead write:

$a += $b;
$a *= 5;
$a -= $d;
$a /= 3;

You can also use this for strings. The following two lines do the same thing:

$sString = $sString . "hello";
$sString .= "hello";

Create a Variable Dump Function

We’re all familiar with print_r which we constantly use as we’re testing our script and figuring out what value our variables currently have. To make this even simpler, you can create a function such as:

function p($var) {
    echo "<pre>";
    echo "</pre>";

This will make sure your variable dump is always enclosed by <pre> tags which are used to make your output much more readable. Additionally, since we can give our function a one letter name, it will be even faster and easier to use.

Use Constants

If you have a variable which never changes, there’s no point constantly re-writing the same thing over and over again. Use constants to define data which you access often like directory paths, error messages etc. I’d recommended giving your constants names which are fully capitalized to help you realize immediately when you’re using them.

define ("DIRECTORY","/path/to/site/");


Use $_GET and $_POST

Avoid using $_REQUEST which gets both POST and GET variables. Use $_GET to get parameters from your URL and use $_POST to get variables submitted from a form:

$sAction = $_GET['actions'];

$sName = $_POST['name'];

This will avoid users manually overwriting variables in the URL which you are expecting to receive from a form.

Use Objects instead of Functions

If you function has lots of parameters, it’s time to move over to objects. I’ve worked on projects that got too complex to maintain after a few of the functions ended up having over 20 parameters! The moment you realize you need to modify the way the function is called, you will need to change each and every function call. So, instead of this:

function getProducts($iParameter1, $iParameter2,
$iParameter3, $iParameter4, $iParameter5,
$iParameter6, $iParameter7, $iParameter8,
 $iParameter9) { ... }

You can use:


Use Method Chaining

If you’re doing multiple object method calls that set variables instead your object, you can use method chaining to make your code simpler. To do this, just end each method with return $this; as shown below:

class User {

    function setThis($iVar) {
        return $this;

    function setThis2($iVar2) {
        return $this;


You will then be able to do method chaining:

$oUser = new User();

That will make your code smaller and neater.

Stop Repeating Code

Don’t repeat any code – If you have a few lines that do the exact same thing, turn them into one function. Or better yet, turn them into an object. Although this might seem like extra work, it will pay off once your application gets bigger and bigger. As a simple example, if you had:

$a = 1;
while ($a < 10) {
    $b = $a * 10;
    $c = $b * 2;
    $d = $c * $b;
    echo $d;

You could write this like this:

function multiply($iVar, $iVar2) {
     return ($iVar*$iVar2);

$a = 1;
while ($a < 10) {
    $b = multiply($a, 10);
    $c = multiply($b, 2);
    $d = multiply($c, $b);
    echo $d;

This is, of course, a super simple example. This will be especially useful for when you have big portions of code that are repeated.

Aim for Loose Coupling, Strong Cohesion

Coupling is the degree in which the change in one component requires a change in another. In other words, if you change one function, will you need to change another? The looser the coupling, the more you will be able to modify components without affecting others. Cohesion, on the other hand, is the degree in which different parts form a meaningful unit. Does your main function do practically everything or do you have many functions which each do very specific jobs? If you do, then you have a strong cohesion. Strong Cohesion happens when your components have clearly defined responsibilities and call other functions for processing which does not form part of their objective.

As a PHP Programmer, you should always aim to create components (functions, classes…) that are both loosely coupled and have a strong cohesion to increase code maintainability and extensibility. Whenever creating a function, try to keep in mind that you might have to use it in other scenarios. Avoid adding code which is highly dependent on other components being set up correctly. Ideally, you should be able to change a system and any other systems depending on it will continue to work without modification.

If we apply this to code, here’s a simple example:

// We want to add two numbers
// only if the first number is
// lower than 5

function add($iVar, $iVar2) {
    if ($iVar < 5) return false;
    else $iResult = $iVar+$iVar2;
    echo "The Result is ", $iResult;

$iVar = 3;
$iVar2 = 2;
add($iVar, $iVar2);

The example above is tightly coupled and has weak cohesion since we are doing validation inside the function itself. We are also putting the result output inside the function itself which will be a problem once we have many functions doing the same and we decide to change the text for it.

Here’s a much better version:

// We want to add two numbers
// only if the first number is
// lower than 5

function add($iVar, $iVar2) {
    return $iVar + $iVar2;

function result($sMessage) {
    return "The Result is " . $sMessage;

$iVar = 3;
$iVar2 = 2;

if ($iVar < 5) {
    echo result(add($iVar, $iVar2));

We can now re-use both add and result functions anywhere in the code. We can also easily modify their functionality without having to modify any other part of the program.

In Summary

The tips above should help you write neater, shorter and more organized code. The examples above were very simple but should help you understand the basics of each concept. If you do not agree with me on any one of them, please go ahead and comment below. We’re all here to learn. :)

Bonus Tip

If you’re a PHP Programmer, the official PHP documentation should be your bible. I would recommend going through the different sections and discovering what each function does. You’ll be amazed at just how much you can achieve with ready-made functions.

Hope you found this post helpful. Leave any comments below. Thanks!

Don't forget to check out more posts from the Tutorial of the Week section.

blog comments powered by Disqus