Best PHP coding practices

PHP is the most used programming language for the web programming.

Outlined are some of the best PHP coding practices.

Use the default PHP delimiters:

Always use <?php ?> to delimit PHP code, not the <? ?> shorthand.

Because PHP is not strongly typed language always use === operator if possible to compare values.

For instance:

$a= "";

if ($a === 0)

echo "equal";

else echo "not equal";

will return “not equal”, else if == is used the return will be “equal”.

Optimize your code only when important.

Analyze your variables

Do use isset(), empty(), or is_null() before working with unknown variables.

Note that isset() determines if a variable is set and not NULL, so it is actually even better to use isset() than is_null()

Try to return integers instead of null or bool

function returnVoid(){



function returnBool(){

    return true;

function returnInt(){

    return 123;


Using the functions this way and obeying the code practice #2 will simplify your PHP experience.

Whenever possible declare and assign your variables and function parameters.

Instead of this line

$mysql = mysql_connect('localhost', 'reinhold', 'secret_hash');

Use this:

$db_host = 'localhost';  

$db_user = 'reinhold';  

$db_password = 'secret_hash';  

$mysql = mysql_connect($db_host, $db_user, $db_password); 

Comparig variables and constants

When testing variable for a value via == operator use the notation

if( constant == $variable), this way you will never make an error like this

if($variable = 5) which will return true.

Use single quoted strings when strings are not having $variables

This is a minor performance benefit, and also a good practice if you work with HTML attributes that should have double quotes (“”) for their names and values.

You can align in array assignments and have the comma (",") at the end

$somearray = array(

    'key1'          => 'value1',

    'key2'          => 'value2',


Use single quote around array indexes

$somearray[key1] is technically incorrect, better is $somearray['key1'].

This is because PHP converts unquoted index to a constant and this takes time so it is faster if you just use quoted key.

Document your code via comments at least

C style comments (/* */) and standard C++ comments (//) are both fine. Use of Perl style comments (#) is discouraged.

tags: & category: -