Another Ten PHP Optimization Tips

I wrote PHP Optimization to improve performance. Now I have another ten PHP optimization tips for you.

1. Single-quoted strings.

Use single quote when possible. It is faster than double quote.
If it is string only, just pick single quotes.

2. The way output data.

Could you point which is the fastest way to output from below?

print "Hi my name is $a. I am $b";
echo "Hi my name is $a. I am $b";
echo "Hi my name is ".$a.". I am ".$b;
echo "Hi my name is ",$a,". I am ",$b;

The last one is actually the fastest operation.

3. Use single-quotes around array indexes.

So, $x[‘sales’] is alway best format and fast.

4. Don’t use short open tags.

<?php is formal tag.

5. Use regular expressions only when you really need it.

When doing string operation, like replace part of string.
strtr is the fastest.

str_replace is faster.

preg_replace is slow.

6. Don’t use functions inside a loop declaration.


for ($i = 0; $i &lt; count($array); $i++) {
<pre class="brush:php">$count = count($array);
for($i = 0; $i &lt; $count; $i++) {

7. Never rely on register_globals or magic quotes.

When building new program, do not use it.

The next three is a good habit for coding, not only for PHP, but to all language coding.

8. Always initialize your variables.

9. Document your code

10. Code to a standard.