PHP best practices guide

PHP is a server-side scripting language designed for web development but also used as a general-purpose programming language. As of January 2013, PHP was installed on more than 240 million websites (39% of those sampled) and 2.1 million web servers. Wikipedia

I present this guide with 15 tips and the PHP best practices, so that your PHP code is as effective as possible:

1. Enable error reporting

Use error_reporting(E_ALL) [link] use it along with ini_set (‘display_errors’, ‘On’) [link] . Use them not only for PHP errors, but also to see all compiler warnings PHP, what methods are deprecated, nonexistent indexes, etc.

2. Do not use short tags

To run the PHP code, it hast to be delimited by <?php ?>. We can configure our PHP (php.ini) to use short tags <? ?> , and the script will run exactly the same. But what happens if we change to another server that are not enabled? Our pages will not work as expected any more, and, what is worse, our source code might be printed on screen as plain text, which could be a major security problem.

3. Comparison operators: === vs ==

The operator == compares the value while === compares the value and type.
Since PHP variables do not have an assigned type and it can be changed “on the fly” at run-time, we should be careful when using each operator.

For example, there are functions that return an integer. As the logical value of any integer is true, except for the zero, which is false, we must take this into account when assessing our conditions. The function strpos() searches the position of the first occurrence of a sub-string within another:

$str = 'Zaragoza';

$seek = 'r'; // Present in $str
$pos = strpos($seek, $str); // $pos = 3

$seek = 'w'; // Absent in $str
$pos = strpos($seek, $str); // $pos = false

$seek = 'Z'; // Present in $str
$pos = strpos($seek, $str); // $pos = 0

Therefore, if we want to verify the presence or not of a string strpos() should not be compared by value (==) but by type and value (===).

4. echo vs print

These functions perform the same task. However, echo is considerably faster than print.

5. Concatenating strings, single quotes (‘) vs double quotes (“)

When working with strings, always avoid using double quotes. PHP analyzes the content of double quotes looking for variables, resulting in a longer run.

6. Search case non-sensitive strings and patterns

The search for a string case non-sensitive stripos() is between 400% and 600% slower than its equivalent case sensitive, strpos(). As for regular expressions, sensitive searches, preg_match(“/ $pattern /”, $string) are, as a rule, slightly more efficient than the equivalent non-sensitive: preg_match(“/ $pattern / i”, $string ).

7. Name conventions

  • Class name in Mixed-Case. Eg. ClassName
  • Methods name in camel-Case. Eg. methodName()
  • Constants in ALL_CAPS. Eg. MAIN_COLOUR
  • Variables, properties and parameters in camel-Case. Eg. $variableInformation
  • ** Non-public method and variables in underscore-prefixed camel-Case. Eg: $_privateVar

**Note: Underscored private methods are not PSR2 compliant, so if in you have to use PSR2, this one is not for you 🙂 [link]

8. Creating Reusable Modules

Code reuse aims to save time and resources and reduce redundancy by taking advantage of assets that have already been created in some form within the software product development process. The key idea in reuse is that parts of a computer program written at one time can be or should be used in the construction of other programs written at a later time.

Avoid having files with hundreds or thousands of lines. Combine the functions that you use frequently in separate Classes/Files and include them.

Eg.

//file1.php

namespace JokiLib;
class Util_Date
{
    public static function timestampToEnglishFormat ($date, 
        $dateSeparator, $timeSeparator = ' at ')
    {
        if ($date == '') { return null; }
        $temp = explode(' ', $date);
        if (sizeof($temp) != 2) { return null; }
        $dates = explode('-', $temp[0]);
        return $dates[2] . $dateSeparator . $dates[1].
            $dateSeparator . $dates[0] . $timeSeparator . $temp[1];
    }
}

So, if you want to convert a date to timestamp format to a format with which we are most familiar, we just do

include file1.php;
echo \JokiLib\Util_Date::timestampToEnglishFormat($myDate, '/');

9. When iterating arrays, sets the maximum value out of the loop

Each call to count() increases up to 50% of the run-time, depending on the size of the array. Then:

// WRONG
for ($i = 0; $i < count ($myArray); $i ++) {
    ...
}
// OK
$limit = count ($myArray);
for ($i = 0; $i < $limit; $i ++) {
    ...
}

10. Use the output buffer

Instead of using echo ‘text’ use ob_start() to start storing the text in the output buffer. To complete the capture, you can use ob_get_contents() and ob_get_clean() , or ob_end_clean(). [link]

11. Including code

Always use include or require instead of include_once or require_once for a better code caching. [link]

Although you shouldn’t be including files. You should use a proper autoloader and traits for reusable code. [link]

12. Character encoding

Use UTF-8 (without BOM) instead of ANSI. What in ANSI can be a particular character (a Spanish “ñ” for example), in other coding can be something else entirely. If your website is available in more than one language, it is essential that your encoding is UTF-8 (including encoding and collation of the database). [link]

Use Multi-byte String (mbstring) functions instead of standard string functions when working with Chinese / Japanese / Korean characters. [link]

13. Use isset()

isset() is not a function but a language construct. This means that PHP will not have to make any previous operation or be overloaded. [link]

For example, if we need to check if a string has a given length we could use strlen().

if (strlen($username) > 5){
}

Since strlen is a function, PHP needs to perform a previous work to execute the call (convert to lowercase and search the hash table functions), and then perform the function itself.

But we could use isset(), and PHP will not have to make any previous operation or be overloaded.

if (isset($username{5})){
}

14. Increase or Decrease variables (++$i vs $i++)

Pre-increase (++$i) is around 10% faster than post-increase ($i++). The reason is that when doing post-increment, PHP needs to create a temporary variable to store the value to be increased.

Note: pre-increase and post-increase have different purposes.

++$aPre-incrementIncrements $a by one, then returns $a.
$a++Post-incrementReturns $a, then increments $a by one.

15. Unset

Use unset() to unset large array variables that are not longer needed

unset($foo);

Conclusion

These are helpful good practices to increase the performance of your code, but keep in mind that being a purist is not always the best way. Unless a system is intended to be scalable, I sometimes will sacrifice speed (milliseconds) for clarity.

Remember, beautiful code is usually good code.

0 0 votes
Article Rating
Subscribe
Notify of
guest
4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Joki
Joki
9 years ago

I present this guide with fourteen tips about the PHP best practices, so that your PHP code is as effective as possible. Your feedback is highly appreciated 🙂

Simon Bennett
9 years ago

I have to say I don’t agree with underscoring,

https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md#42-properties

“Property names SHOULD NOT be prefixed with a single underscore to indicate protected or private visibility.”

Joaquín Ruiz
8 years ago
Reply to  Simon Bennett

I think that with underscore camel case the code is easier to read, that’s my opinion, not a fact. Actually Codeigniter recommends it; but I think is up to the developer to use it or not.

4
0
Would love your thoughts, please comment.x
()
x