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:
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
if(!$user_login){
header("Location:https://www.macronimous.com/");
die();
}
This not only increases the execution time but also makes the coding long and complex.
For example,
<?php
If (condition1==true){
code which satisfies the above condition
} else {
perform die(); or exit();
}
?>
The same set of codes can be written as:
<?
if(!condition){
// 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
<?php
$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.
<?php
If(mysql_num_rows($res)>0) {
while($a=mysql_fetch_object($res)){
echo $a->first_name;
}//ending of while loop
}//ending of if condition
?>
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:
<?php
echo "<table>";
echo “<tr>”;
echo “<td>”;
echo “Hai welcome to php”;
echo “</td>”;
echo </tr>”;
echo “</table>”;
?>
Instead of the above we can simply say,
<html>
<body>
<table>
<tr>
<td><?php echo "Hai welcome to php"; ?></td>
</tr>
</body>
</html>
Here the PHP compiler would execute the particular server code only, here in the example, , 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.
For example
$sql="select first_name,last_name,email_address from tbl_user where user_id=".$user_id." and member_type='".$member_type."'";
mysql_query($sql);
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.
Instead,
$sql="select first_name,last_name,email_address from tbl_user where user_id="%d" and member_type='"%s"'";
mysql_query(sprintf($sql,$user_id,$member_type));
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.
It is always better to use arrays in PHP, as they are quite easy to manage and easily understandable as well.
<?php
$products=array("Dove","Apple","Nokia");
?>
Using Split array is also a very good way of coding in PHP. However, there are ways to use a split array:
Rather than:
<?
for($iC=0;$iC<count($products);$iC++){
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.
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.
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){
$this->items[$cart_number]+=$quantity;
}
}
// Call the class function
$cart=new shopping_cart();
$cart->add_product_item("123",10);
?>
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");
while($obj=mysql_fetch_object($res)){
echo $obj->column_name1;
}
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:
if($checking_value1==$value){
echo "result1";
}elseif($checking_value2==$value){
echo "result2";
}elseif($checking_value3==$value){
echo "result3";
}else{
echo "result 4";
}
The same thing can be expressed in a simpler way using the switch case, which greatly reduces the operational time:
switch($checking_value){
case Value1:
echo "result1";
break;
case Value2:
echo "result2";
break;
case Value3:
echo "result3";
break;
default:
echo "result4";
break;
}
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 :’.$serialno.’. 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.
Thank you for reading ! Please share if you liked it!
#php #laravel #security #web-development