Today's PHP tip: 'Using single quotes'
When echoing text or assigning variables, your script will execute faster if you use single quotes (apostrophes) instead of quotation marks around text which does not contain variables.
For example, consider the following two statements:
echo 'Hello, world, this is a test!';
echo "Hello, world, this is a test!";
Execution of the first statement will be faster than that of the second. When PHP sees a literal string surrounded by quotation marks (double quotes), it takes time to interpret the string and determine whether or not it must be expanded by replacing variable names with their contents. PHP does not perform this step when it encounters a literal string expressed within single quotes.
Accordingly, strings surrounded with single quotes will not be expanded. In the following example,
$var = 'good day';
echo 'Today is a $var!';
...The result would be "Today is a $var," as PHP would not replace the $var with "good day" in the single-quoted string.
Of course, the speed difference is negotiable; we're talking milliseconds or even picoseconds worth of execution time for either statement on a fast server. However, the speed improvement in large scripts, e.g. those which contain several hundred or several thousand assignment or echo statements, can be noticeable.
When writing a MySQL query, it is not necessary to use escaped double quotes (\") when representing literal strings within the query. Single quotes (apostrophes) will work fine. For example, the following two lines of code will perform the same query:
$result = mysql_query("SELECT foo FROM bar WHERE baz=\"test\"", $db);
$result = mysql_query("SELECT foo FROM bar WHERE baz='test'", $db);
As will this code perform the same query:
$var = 'test';
$result = mysql_query("SELECT foo FROM bar WHERE baz='$var'", $db);
There is not necessarily a performance gain between one method or the other, but using single quotes instead of escaped double quotes greatly improves the readability of your code.
Looking for quality PHP scripts at a price that won't break the bank?
Check out
PHP Labs for professional scripts and thousands of webmaster resources.