Here’s my top 5 simple PHP optimization techniques to develop faster and better code –

1. Use pre-calculations for loops. Example:

Wrong:

<?php
for ($ctr = 0; $ctr < count($myArray); $ctr++)
{
// ...
}
?>

Right:

 <?php
$total = count($myArray);
 for ($ctr = 0; $ctr < $total; $ctr++)
 {
 // ...
 }
 ?>
 

Since count($myArray) is not going to change whilst the loop runs, there is no need to recount entire array on each iteration of the loop.

2. Use echo instead of print – it’s faster

3. Close database connections once you’ve used them. Don’t leave them for PHP to clear up.

4. When using header(“Location:…) ensure you implement a die(); immediately after, as the PHP script continues running unnecessarily even though the browser has been redirected.

5. Unset/destroy instantiated classes, large arrays, strings and other variables once complete – they hold on to memory until the script completes.

Most of the optimization hints above are not PHP dependent either but apply across the board to programming in general.