how to write a Clean and Effective PHP Code.

how to write a Clean and Effective PHP Code.

Any code when written in a clean, easy to understand and formatted way is readily accepted and acclaimed by one and all. It is essential that the codes we write should be able to be understood by all, because the same programmers need not necessarily work on the same set of codes always. For easy identification and understanding of the codes for any programmer who works on it later, it is essential that the codes are structured, clean, secured and easily maintainable.

Explained below are few of the best practices that are followed to maintain clean and easy to understand PHP codes. They are not in any order of importance, so all are the practices mentioned are essential and carry equal importance:

1.Commenting on every important action that is performed is very essential.

This not only helps in easy identification of the need of that particular code, but also gives a neat look to the codes as well.

// Function for login checking


2.Avoid unwanted usage of conditional statements:

This not only increases the execution time but also makes the coding long and complex.
For example,

If (condition1==true){
    code which satisfies the above condition
} else {
    perform   die(); or exit();


The same set of codes can be written as:

// display warning message.
die("Invalid statement");

This reduces the execution time and also makes the codes easily maintainable.

The same can also be written as

$response_text = ( $action == "edit" ) ?  "the action equals edit" : "the action does not equal edit";
echo $response_text;

Here ternary operators have been used, instead of using conditional statements, to simplify the coding further.

3.Code indentation, in order to highlight statement beginnings and endings.

If(mysql_num_rows($res)>0) {
echo $a->first_name;
}//ending of while loop
}//ending of if condition

4.Avoid unwanted html tags in the PHP code:

In the example given below, the PHP compiler goes through each and every line of the code and executes the function, which is time consuming.

For example:

echo "<table>";
echo “<tr>”;
echo “<td>”;
echo “Hai welcome to”;
echo “</td>”;
echo </tr>”;
echo “</table>”;

Instead of the above we can simply say,

<td><?php echo "Hai welcome to"; ?></td>


Here the PHP compiler would execute the particular server code only, here in the example, <td><?php echo “Hai welcome to php”; ?></td>, instead of creating html tags, as the html codes are alien to PHP. This facilitates in cutting down unnecessary checking time of the PHP compiler, thereby saving code execution time.

5.Clear Code with in assigning values to Mysql Arguments:

For example

$sql="select first_name,last_name,email_address from tbl_user where user_id=".$user_id." and member_type='".$member_type."'";

In the above example, you can see that the PHP values are included in the query condition. Also there are lots of concatenations done to the variables within the query.


 $sql="select first_name,last_name,email_address from tbl_user where user_id="%d" and member_type='"%s"'";

By using this query, the values are automatically assigned to the appropriate positions, thereby saving the execution time and as well as the programmers can easily find the related values to the arguments passed.


6.Using Arrays:

It is always better to use arrays in PHP, as they are quite easy to manage and easily understandable as well.


Using Split array is also a very good way of coding in PHP. However, there are ways to use a split array:
Rather than:

echo $products[$iC].”<br>”;

Instead, the codes can be written as follows:

foreach($products as $product_value){
echo $product_value;

foreach is specifically for arrays. When it is used, they reduce the coding length and also the functioning time.

7.Consistent naming:

It is always advisable to name classes, objects and others consistently. This helps in easy identification for other programmers who might work later on the project. Also names of files in local directories should also be easy to understand.

8.Using Objects [class]

Though they seem to be quite complicated to the newcomers, Objects are very useful as it reduces code repetition and also facilitates easier changes to the codes. In that when a class is used, it makes it more flexible to work with.

A simple class functionality is explained below:

Class shopping_cart{
var $cart_items;

function add_product_item($cart_number,$quantity){
// Call the class function
$cart=new shopping_cart();

9.Appropriate use of Looping codes:

There are many looping codes available in PHP. It is very important to choose the right looping code for the right purpose, so that execution time can be saved upon and the work also would get over sooner.

For example, instead of:

$res=mysql_query("select * from tbl_products");
for($iC=0;$iC< mysql_num_rows($res);$iC++){
echo mysql_result($res,$iC);

The same can be coded this way, in order to reduce the execution time:

$res=mysql_query("select * from tbl_products");
echo $obj->column_name1;

10.Using of case switches:

It is definitely advantageous to use Case switches instead of If conditions. This is because switch statements are equivalent to using a series of IF statements on the same expression.

Example of using a series of If statements:

echo "result1";
echo "result2";
echo "result3";
echo "result 4";

The same thing can be expressed in a simpler way using the switch case, which greatly reduces the operational time:

case Value1:
echo "result1";

case Value2:
echo "result2";

case Value3:
echo "result3";

echo "result4";



11.Using single codes instead of double quotes:

Though these two serve various purposes, using single quotes help in faster execution of the loops than when using double quotes.

For example, a simple example of printing 1500 lines of information, can be done in two ways as:

//Using double quotes
print “SerialNo : $serialno. WorkDone : $workdone. Location: $location”;

The same can be written with single quotes:


//Using single quotes
print ‘SerialNo :’.$serialnop.’. WorkDone : ‘.$workdone’. Location‘.$location’.';

Here, the second line of codes works much faster than the first one, where the strings have to be analyzed completely, all the 1500 times. In the second line of codes, no actual string analyzing takes place. Just combination of the strings happens in order to make the printing possible.

Few of these tips might sound quite familiar, but they have been included here in order to refresh the best practices that can be followed to get clean, secured at the same time easy to maintain PHP codes.

About author

You might also like

PHP Coding Help 0 Comments

PHP – Send emails correctly to keep spam filters away

Ok, so you’ve set up a nice mail form on your remotely hosted PHP site, but every time you send an email to someone through it, it seems to get

Tricks and Tips 0 Comments

Bypassing PHP security (addslashes) while SQL injection attacks is possible

Hello Again, Here I completed this article.. I apologize because I took bit more time to complete this after announcing. As I said

PHP Coding Help 0 Comments

how to display the title of page in that pages specific URL/link?

Question to me : Hi, I’m new to PHP and I took on the challenge to build a simple