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.
- Use
<?php ... ?>
tags for PHP. All other formats are depreciated including short tags.
- It is very useful to use Unset or null your variables to free memory, especially for large arrays.
- 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.
- echo is faster than print. So avoid using ‘print’ often.
- “else if” statements are faster than select statements aka case/switch.
- Use sprintf instead of using variables contained in double quotes, it is about 10x faster.
- Turn on mod_deflate in Apache v2 to reduce the use of bandwidth. For Apache v1 try mod_gzip.
- Avoid using string concatenation. Preferred method is echo’s multiple parameters (or stacked).
- 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.
- Avoid using magic methods like __isset(), __unset(), __sleep().
- Avoid require_once() and use require() where possible.
- Better to Use full paths in includes and requires.
- 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.
- Since PHP5, the script execution start time can be found by $_SERVER[’REQUEST_TIME’], so avoid using time() or microtime().
- PCRE regex is quicker than EREG, but always look out if you can use
quicker native functions such as strncasecmp, strpbrk and stripos
instead.
- 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.
- Error suppression with ” @ ” is very slow.
- 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.
- $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.
- It is always better to close your database connection after the use.
0 comments:
Post a Comment