Sunday, July 26, 2009

A rant on PHP, quotes and variables

Here are 3 ways to display some text with some PHP variables:

single quotes interspersed with vars:

echo 'My name is ' . $user
. ' and I eat ' . $food['favorite'] . '.';


double quotes interspersed with vars:

echo "My name is " . $user
. " and I eat " . $food['favorite'] . ".";


double quotes with embedded vars:

echo "My name is {$user} and I eat {$food['favorite']}.";

The vast majority of PHP code I come across uses the first two methods, breaking in and out of quotes for each variable. IMHO the third way much easier to read and maintain. Granted there are slight performance differences between them, but not enough to be concerned about. I think the reason that version 3 isn't so popular is because most PHP developers don't learn this type of curly-brace syntax (enabling you to embed complex variables into quoted strings) right away, and therefore rarely think to use it.

Of course you can take things a step further with sprintf and really keep things tidy. Let's take a SQL query for a common example.

Here is the "messy" way:

$sql = "select * from MYTABLE where id=" . (int)$info['id'] . " and firstname = '" . mysql_real_escape_string($info['firstname']) . "' limit " . (int)$limit;

And the much cleaner way:

$sql = sprintf("select *
from MYTABLE
where id=%d
and firstname = '%s'
limit %d",
(int)$info['id'],
mysql_real_escape_string($info['firstname']),
(int)$limit
);


I hope I brought some ideas to light, happy coding.