Top 20 PHP Tips and Tricks for beginners

PHP tips

PHP tips to improve PHP skills

Hi people, in this post i’m gonna deliver you some interesting quick tips to explore and improve PHP skills. Try to follow these tips when you code.
  1. Use <?php ... ?> tags for PHP. All other formats are depreciated including short tags.
  2. It is very useful to use Unset or null your variables to free memory, especially for large arrays.
  3. It is better to wrap you strings in single quotes (”) instead of double quotes (“”). Beacuse PHP looks for variables into double quotes.So unless you’re gonna use a variable inside, don’t use doubles quotes for variables.
  4. echo is faster than print. So avoid using ‘print’ often.
  5. else if” statements are faster than select statements aka case/switch.
  6. Use sprintf instead of using variables contained in double quotes, it is about 10x faster.
  7. Turn on mod_deflate in Apache v2 to reduce the use of bandwidth. For Apache v1 try mod_gzip.
  8. Avoid using string concatenation. Preferred method is echo’s multiple parameters (or stacked).
  9. Avoid using pre-calculated functions in loops. for eg. for($i=0; $i< count($array);$i++) This will call count function each time. So store it in a variable like this $count = count($array); before the loop starts.
  10. Avoid using magic methods like __isset(), __unset(), __sleep().
  11. Avoid require_once() and use require() where possible.
  12. Better to Use full paths in includes and requires.
  13. require() and include() are same in all the ways. One different is require will halt if the file is missing. Performance wise there is a very little difference between them.
  14. Since PHP5, the script execution start time can be found by $_SERVER[’REQUEST_TIME’], so avoid using time() or microtime().
  15. PCRE regex is quicker than EREG, but always look out if you can use quicker native functions such as strncasecmp, strpbrk and stripos instead.
  16. Try xml2array when parsing XML in PHP, which makes use of the PHP XML functions, for HTML you can try PHP’s DOM document or DOM XML in PHP4.
  17. Error suppression with ” @ ” is very slow.
  18. str_replace is faster than preg_replace. str_replace is best overall, however strtr is sometimes quicker with large strings. Using array() inside str_replace is usually quicker than multiple str_replace.
  19. $row[’id’] is 7x faster than $row[id], because if there is no quotes PHP has to guess which index you meant, assuming you didn’t mean a constant.
  20. It is always better to close your database connection after the use.

0 comments:

Post a Comment

www.comhttp.blogspot.in. Powered by Blogger.