10 Tips to Master the Art of Writing PHP Code

PHP has become one of the most widely used languages among developers for developing web applications, such as Facebook, WordPress, and other popular resources.

However, you might find coding in PHP challenging and a daunting task, especially when you're just a novice. So, to save you from making mistakes when writing PHP code, I've listed some great tips that will help you work on PHP language a lot easier.

Mastering PHP

1. Ditch the Use Of <? … ?>

When starting to write a PHP script, the standard code declaration blocks use “<? php … ?>” script delimiters. However, beginners can make the mistake of writing the script delimiters as <? ... ?> instead of <?php ... ?>. Make sure to avoid such a situation. That's because, <? ... ?> when used in a PHP script may work on your server, but fails to work on other servers.

Secondly, you must avoid the use of shortcut tags when echoing a variable. That's because, those tags aren't supported everywhere. You may find it hard to prevent the use of shortcut tags, but doing so can help in making your code more portable.

Basically, you just need to avoid writing your PHP script only with shortcut tags such as <?=$Var?>. You should rather write it as <?php echo $Var ?>.

2. Understand the Difference Between Comparison Operators

Comparison operators are an extremely useful part of PHP. But let's face it, some programmers fail to determine the difference between comparison operators, such as '==' and '==='. Remember that == is for equality and checks whether the value on the left and right side are equal. On the other hand, === not only looks for whether the values on both sides are equal, but also checks whether the variable type is the same on both sides or not.

Let's have a more detailed understanding of when you need to use the === comparison operator. For this purpose, consider an example of PHP code that requires using the strpos() function – that may return 0, which means that the string you've been looking for is located at the 0th index. Or else, it will be present at the first position of another string. Now, since zero is considered to be equal to FALSE in PHP, clearly from the result of strpos() you won't be able to tell if something is at the beginning of a string or the function couldn't find anything.

//This is an example of bad code 
if ( strpos( $inputString, 'abc' ) == false ) {
  // do something
 }

//This is an example of good code
if ( strpos( $inputString, 'abc' ) === false ) {
  // do something

 }

3. Replace If/Else With Ternary Operators

Rather than making use of an if/else statement, it would be better if you use a ternary operator instead. Here's a line of PHP code that explains ternary operator usage:

$todo = (empty($_POST[’todo’])) ? ‘default’ : $_POST[’todo’]; 

This line of code is equivalent to the following if/else statement:

if (empty($_POST[’todo’])) {
$todo = ‘default’;
} else {
$todo = $_POST[’todo’];
}
?>

So, as you can see in the code above the ternary operator helps in making the code clutter-free and saves plenty of space, by writing the same code using the if/else statement in a single line.

4. Use Relevant Variable Names

This is the most obvious step you should follow when writing PHP code, ensure using variable names that add some value. Furthermore, include details about the data that those variables will store. Let's assume, you need to use a variable as an integer. In that case, you must use a variable name with an “i” at the beginning. In fact, this is a crucial factor you must consider when writing PHP code, since we don't require specifying a type during variable declaration in PHP.

Note: Though you can choose to use a variable name in caps or small letters, it is recommended that you focus on capitalizing the first letter of your variable.

Below is a list of some meaningful variable names:

$iNum = 12; // For Integers

 
$fPi = 2.121956; // For Floats
$sName = "Mac"; // For Strings
$bIsMember = false; // For Booleans

5. Add Comments Alongside Each Important Action

Adding comments side-by-side to each important action will help you identify the need for any specific PHP code snippet, especially when you are handling a large size project. In addition, commenting helps make the code look neat and easy to understand to other programmers working on the same project as you.

// Function to Check Login
if(!$user_login){
header("Location:http://www.yoursite.com/");
die();

} 

6. Use “str_replace()” Instead Of “ereg_replace()” and “preg_replace()”

If you need to improve the efficiency of your PHP code to replace strings, consider using str_replace() instead of using functions, such as: ereg_replace() and preg_replace(). In fact, according to an online report, “str_replace() is 61 percent more efficient compared to other regular expressions.”

But, in case you are using regular expressions, then ereg_replace() and preg_replace() will work faster compared to str_replace().

7. Consistent Naming Convention

Using consistent naming conventions is considered good coding practice. Mostly, writing classes, objects, etc. consistently makes it easy for your team members to work on your project without much confusion. Besides this, make sure that the files saved in local directories have an easy-to-understand name.

8. Use isset() Over strlen()

When checking out the length of a string, consider using isset() over strlen(). That's because, the isset() function will help in making calls 5 times quicker. Another great advantage of using isset is that your function call will remain valid regardless of whether the variable exists or not.

Here's a simple example to demonstrate the use of the isset() function:

if (isset($username[8])) {
 // The username is at least nine characters long.
}

9. Prefer Using Single Quote Rather Than Double Quotes

While both single, as well as double quotes, serve several purposes, it is advised that you should use single quotes over double quotes. This is because the first option helps in executing the loops a lot faster. Let us see two different ways of printing long lines of information:

//Using double quotes
print “WorkStatus : $workstatus. Location: $location”;

Now, let's check how the above line of code can be written using single quotes:

//Using single quotes
print ‘WorkStatus : ‘.$workstatus’. Location‘.$location’.';

10. Utilize a Framework

And lastly, the best way to work on a PHP project is to make use of a PHP framework such as Laravel, CakePHP, Yii, Symfony, CodeIgniter and many others. Using any one of these frameworks can help reduce the time in performing repetitive tasks when developing a site or a web application. Moreover, less code means you can debug and test your built web solutions quickly.

In essence, PHP frameworks help get rid of the overheads in building web apps.

Conclusion

Hopefully the tips discussed above will help you write efficient PHP code in a neat and more organized way. The tips included in this post are simple, so make sure to explore the topic more to have better familiarity with each concept.

Opinions expressed in this article are those of the author and not necessarily those of Onextrapixel.