Published in


PHP Programming Best Practices and Coding Styles

Best Practices and Coding Styles to learn to become a better PHP Programmer

1. Avoid short PHP tags

Short tags (<? ?>, <?=?>) are easy to use, but it is not always reliable, because short tags can be disabled using the short_open_tag ini setting and not all servers are enabled it by default. So the code written in short tags is not portable across servers unless you have access to the ini settings. Another reason to avoid short tag is it may confuse with <?xml ?> notation. The recommended use of the PHP tag is <?php

// My super portable code goes here
// My code that may not work on all servers
<% %> <%=%> // ASP style tag support in PHP
<script language="php"> </script>

2. Avoid closing tag in PHP only files

If your file contains only PHP code, the closing tag (?>) is optional. It is recommended to avoid closing tag because it prevents unwanted white-space or new lines being added at the end of files. That is handy to use output buffering and we will be able to add headers to the response later.

3. Code Formatting and Layout

It doesn’t matter in-terms of code execution if we didn’t format the code well. But it does matter, when another person came to read it or another team try to update it or even worst when we come back to review our own code after a long time.

function calculate($a, $b, $c) {
$result = 0;
$x = $a + $b;
if($x >= $c){
$result = ($a + $b) * $c;
$result = $a * ($b + $c);
return $result;
function calculate($a, $b, $c) { $result = 0;
$x = $a + $b;
if($x >= $c){
$result = ($a + $b) * $c; }else{
$result = $a * ($b + $c); }
return $result;

4. Write Comment Code

Comments are the part of code that helps to describe what is a piece of code or a function or a class is doing. Writing comments is a good practice to let others know what you’re doing or to remind yourself what you did. You don’t want to comment every line in your code but do when you think it is necessary to understand your code later.
These are the examples of commenting styles on PHP

echo 'Hello World 1'; // A single line comment
echo 'Hello World 2'; # Another way to do a single line comment

This is a multi-line comment
Its cool when I want to write an essay about my code
echo 'Hello World 3';

5. Choosing Names

Naming your variables, functions, or classes are important. While naming, you should consider these factors

  1. The name you chose should be meaningful
  2. The name should be in a language everybody will understand (preferably in English)
  3. Follow consistent naming convention
  • ClassName
  • function_name
  • $variable_name

6. Understanding ‘echo’

The PHP echo statement is a language construct (not exactly a function) used to output data to the screen. echo and print both do the same thing, but echo is a little faster. echo can take multiple parameters, and it is faster than concatenating strings.

echo "Hello ", $name, "!";
echo 'Hello ' . $name . '!';
echo "Sum: ", 1 + 2;
echo 'Sum: ' . (1 + 2);
($some_var) ? echo 'true' : echo 'false';
echo $some_var ? 'true' : 'false';

7. Using variables

It is not necessary to initialize variables in PHP however it is a good practice. Uninitialized variables will have a default value, relying on the default value may end up in unexpected results of your program. So it is recommended to initialize your variables before using them, and that will make your code much cleaner.

$my_array = array();
$my_integer = 0;
$my_boolean = false;
$my_name = $data['name']; 
echo $my_name;
echo $data['name'];

8. Use of Ternary Operators

A simple if/else statement can be changed to make use of ternary operators. It makes your code shorter, readable and saves few lines too. The usage is simple…

// Usage of Ternary Operators 

// Similar if/else condition usage in one line
if(CONDITION) { $variable = IFTRUE; } else { $variable = IFFALSE; }
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];
if (empty($_POST['action'])) {
$action = 'default';
} else {
$action = $_POST['action'];

9. Use of Comparison Operators

PHP have strict and loose comparison operators, the difference is strict comparison validates value and type while loose comparison only validates value. You can use any of the comparison, but to avoid unexpected program behavior, you should be very clear what you are doing.

// Pass if $_POST['user_id'] is an integer 1234 or a string '1234'if($_POST['user_id'] == '1234'){  
echo 'Hello Special user';
// Pass only if the function IsThisAdmin() return a boolean trueif(IsThisAdmin($_POST['user_id']) === true){
echo 'Hello Admin';
if (strpos('abcdef', 'a') !== false) {
echo 'string found'; // Found, thanks to operator !==
} else {
echo 'string not found'; // Not found, thanks to operator !==

10. About Strings

Let us take a look at common ways of specifying strings and its use in PHP.

Single quoted

Enclosed in single quotes (') is a simple way to specify a string. It doesn't parse any special characters, but it allow escape character with a backslash (\), generally for escaping a single quotes and backslash itself in the string. So this way is ideal if you want to output a special character literally, such as \r or \n, and this method is good if you have a simple string to specify.

echo 'Hello, \n this is a newline'; 
// Outputs: Hello, \n this is a newline

Double quoted

Enclosed in double-quotes (") is a another way to specify a string, and PHP will interpret more escape sequences for special characters. So \n in the string really output a newline instead of literally printing it. And variables specified in the string will be parsed and replaced with its value, if available. This method is ideal if you have to specify variables or special characters in your string.

$name = "Dipu Raj";

echo "Hello, My name is $name";
// Outputs: Hello, My name is Dipu Raj

echo "See the first character of my name '{$name[0]}'";
// Outputs: See the first character of my name 'D'

11. About Arrays

Array in PHP is optimized for several different uses, it can be used as an array, list, hash table, dictionary, collection, stack, queue, etc. Let’s look into some cool features of PHP Array probably don’t use commonly.

// Short array declaration syntax, as of PHP 5.4
$my_array = [1, 2, 3, 4];
$my_array_2 = ['one' => 1, 'two' => 2, 'three' => 3, 'four' => 4];

// Regular array declaration syntax, all PHP versions
$my_array = array(1, 2, 3, 4);
$my_array_2 = array('one' => 1, 'two' => 2, 'three' => 3, 'four' => 4);
echo $my_array[2];
echo $my_array{2};
function getColors() {
return array('red', 'blue', 'green', 'yellow');

// As of PHP 5.4
$second_color = getColors()[1];

// Previously it was only possible using a temporary variable
$tmp = getColors();
$second_color = $tmp[1];
foreach ($my_array as $key => $value)
echo 'Key: ', $key, ' Value: ', $value;
// PHP 5
foreach ($colors as &$color) { // &$color pass by reference
$color = strtoupper($color);

/* Make sure to unset the reference variable,
it may affect the array value if the variable $color is modified elsewhere in the code */
unset($color); // Unset the reference variable

// Older versions workaround
foreach ($colors as $key => $color) {
$colors[$key] = strtoupper($color);
echo $my_array_2['three']; // Correctecho $my_array_2[three]; // Wrong code


I hope that the tips and practices discussed here was helpful to you. However, programming is vast, don’t stop learning, try new things and be up to date. If you think there is an incorrect information or missing clarification, please let know with your comment.



Smart, free and open-source jQuery plugins

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Dipu Raj

Full stack engineer. Believes the code should be as beautiful as the design.