PHP Optimizations

PHP is my favourite web development language.(Not anymore, its Python now). Nevertheless, here are a few tips I follow to make PHP work faster :

  • When you’re creating PHP files, you’ll start with <?php tags as usual, but DON’T end the file with ?> tags if its not your main index.php file. Its optional and ignoring it is not just safe but recommended. So always leave the <?php tags unclosed in files which you are going to include in your main file. Do close it properly in your main index.php file though.
  • Don’t use functions in FOR loop condition if the function returns the same result always e.g.
for($i=0; $i&lt;length(arr); $i++)


for($i=0, $N=length($arr); $i&lt;$N; $i++)

That’s because since the condition is checked on every iteration. The function is called again and again to check the lenght of the same array every time. Instead since you know the array length is the same, why not save it in $N so that it won’t have to calculate it again and again. Though if your array $arr may change in length, you can use that.

  • Initialize all variables before using, just like C++. Although PHP allows uninitialized variables, DO NOT use them. Don’t forget, this is one of the most important optimizations.
  • There are global variables in PHP which you access via : global $var; . But if you’re operating on global variables more than twice in the same function, then its better to copy them into a local variable and then do it and then update it again on the global variable. Operating directly on the global variables is quite slow.
  • By the way, try to avoid using global variables altogether. Don’t declare your variables global unless you really don’t have any other option left.
  • If you’re using boolean expressions, then use “true” instead of “TRUE” and “false” instead of “FALSE” (quotes for clarity). Although both behaves the same, but small lettered ones are faster (yes, I know, but its true!)
  • Don’t create variables to store temporary data unnecessarily if you can easily avoid them e.g. $tmp = func(); return $tmp; Instead use : return func();
  • Just an optional optimization : Static methods are faster than non-static. If you think your method can be made static, make them. Though no compulsion in this particular case.
  • Although PHP will automatically destroy variables when their scope ends, still if you’ve created some big variable with huge amount of data, use unset($var) to free memory as soon as you no longer need that variable. Don’t wait for the scope to destroy it. Again, this is also optional and apply it only if you feel your variable can be that huge.
  • Avoid using require_once,include_once,__autoload,__get,__set . They’re very costly.
  • If you’re using include and require, give full paths instead of relative paths to avoid PHP wasting time in resolving OS Path.
  • Try to avoid regular expressions matching, they’re very slow. If you want to use simple validation, check out the ctype API. It can be found under section “Function Reference” > “Variable and Type Related Extensions” > “Ctype” in the PHP Manual. I hope you’ve downloaded PHP Manual. There’s no best way to learn PHP than from the Manual. It has lots and lots of examples.
  • Don’t suppress errors (if you intend to) using ‘@’ in front of functions. They’re very slow.
  • Whenever you’re creating strings, use single-quotes instead of double-quotes wherever possible. But remember that you cannot put variables inside single-quotes strings, in that case use double-quotes. e.g.

$hello=" Hi $name, How are you? ";

return $hello;



$hello=" Hi $name, How are you? ";

return $hello;

MORE optimization can be done by avoiding $hello variable and directly putting that in the return statement like

return " Hi $name, How are you? "
  • Use ‘foreach’ loops instead of ‘for’ loops wherever possible
  • Use ‘while’ loops instead of ‘for’ loops wherever possible and if you can’t even use ‘foreach’ loops there
  • Instead of concatenating strings during echo, use the echo comma operator e.g.
echo $hello.$name." You last logged in on $time". $bye;


echo $hello,$name,"You last logged in on $time",$bye;
  • echo is quite slow. So don’t echo many times. Instead as I mentioned in my last point, get all the variables and then pass them in a single echo command using the comma operator.
  • There are some pretty cool PHP extensions available out there. One of them is Memcache that will cache your PHP generated HTML pages and if there’s a HIT in the cache on a page request, your PHP code will not have to be reinterpreted. Caching can improve your code performance by 200 – 300 % ! There are other caching softwares also like PEAR Cache, Cache Lite, etc. Check it out under “Appendices” > “Extension Categorization” > “External Extensions” > “Memcache” in the PHP Manual.
  • Output buffering is another way to optimize transportation of HTML output to the user. You can use the ob_start() function in the beginning of the code and all the echo functions after that will not actually send the output to the client, but will send it to the output buffer. Once you’re echoing part is done, use ob_flush() to send the data to the client in one go. You won’t need this though if you apply the comma-separated echo trick properly. You can learn more about it under section “Function Reference” > “Affecting PHP’s Behaviour” > “Output Control” in the PHP Manual.
  • Another way is to compress your HTML code before sending it to the client. A ob_start(“ob_gzhandler”); in the beginning of your code will do the trick and similar ob_flush() can be used to send the compressed output. But note that while this will save the network bandwidth, it will increase the computation load on your CPU for compression. So there’s a trade-off in this case.
  • Now something about SQL queries, DO NOT USE mysql_query() inside a loop ! Instead, first build the query using the loop and then use a single mysql_query() to execute it.
  • But actually, for security reasons, don’t use mysql_query() at all and use Prepared MySQL queries. This will not only relieve you from having to worry about SQL injection attacks, it will also does some query optimization at its end to server you better. PHP already comes with PDO support. Check it out under “Appendices” > “Extension Categorization” > “Bundled Extensions” > “PDO” in the PHP Manual
  • Enabling Apache’s mod_deflate and mod_gzip can also help.
  • Set “AllowOverride” to “None” in the Apache configuration if you actually don’t need it.
  • Always put static pages into a separate server than the one hosting your PHP codes. And use some fast filesystem server to access them like thttpd.

That’s all I could think of for now. More tweaks can be done from Apache’s side also to improve the performance.

3 comments on “PHP Optimizations

  1. Hello,

    very good article.

    One question if you dont mind. In wordpress we are all the time using the_title(), the_permalink(), per instance get_permalink ( $post->ID ); or basename (get_permalink ( $post->ID ));

    Do you think that is better to store all these functions in variables or directly call it each of the dozens of times that they are called in an average wordpress theme?

    Thanks and regards

    • Well, that depends. The length() function example which I gave is a PHP core function and it calculates the length of the array every time its called. Whereas the wordpress functions which you said above may not work like the same. Instead those functions may have simply returned the value of the variable in their data structure and so its not that costly as the functions which recalculates that variable.

      But still, calling a function takes some overhead. If you’re calling those functions multiple times in the same block, then using a local variable in place of it will surely speeden up your code.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s