In this tutorial I will try to write some basic tips on how to optimize your php code. In general those are some very basic information that can make your writing style better, and your code run faster.
Strings
As you may know strings can be defined using two styles, the single and the double quote. For best performance use single quoted strings. This is faster as the single quoted strings are not parsed while the double quoted strings are parsed for special characters and variables.
Example :
This :
$a = '123' . $b ;?>
is faster than this :
$a = "123$b";?>
Optimizing if statements
For simple if statements you can always use the ? operator.
Example code :
$a = $b>1 ? true : false;?>
This would be :
if ( $b > 1 )
$a = true; else
$a = false; ?>
Optimizing loops
In general for ($i=0;.....) is faster than foreach(...) but of course foreach is much easier to use when you code. Here is an alternative that is faster from both :
while ( $val = array_shift($array) )
echo $val;?>
This example will extract the first value from the array so it will also free up some memory in the process.
Optimizing your php application
Php is a server side scripting language (duh?). That has many advantages but some disadvantages too. A common problem is that you can write an application that works in a server, but it doesn't work in another server. To avoid problems like this you should :
Use relative paths. Eg. include './file.php'; or include dirname(__FILE__) . '/file.php'; or include $_SERVER['DOCUMENT_ROOT'] . '/file.php';
Do not use globals. To use get variables, call the $_GET array, for post variables the $_POST array, etc.
Allways check if an extension is loaded before you use it. Example : if (!extension_loaded('curl')) die('CURL is not loaded');
Hope this small tutorial will help you write better code in the future. Enjoy :)