This is a very simple trick to make code more readable, and provides no speed implications… or does it?
Starting code … this is a trivial example just to show the concept …
.
echo "<ul>\n";
echo "\t<li>one</li>\n";
echo "\t<li>two</li>\n";
echo "\t<li>three</li>\n";
echo "<ul>\n\n";
1st improvement: As indicated before double quotes is slower, especially if you are not putting in variables, i pretty much always use single quotes…
.
echo '<ul>' . "\n";
echo "\t" . '<li>one</li>' . "\n";
echo "\t" . '<li>two</li>' . "\n";
echo "\t" . '<li>three</li>' . "\n";
echo '<ul>' . "\n\n";
2nd improvement: multiple echos slower than storing as variable then just printing that …
.
$list = '<ul>' . "\n";
$list .= "\t" . '<li>one</li>' . "\n";
$list .= "\t" . '<li>two</li>' . "\n";
$list .= "\t" . '<li>three</li>' . "\n";
$list .= '<ul>' . "\n\n";
echo $list;
3rd improvement: doesn’t that really look ugly … well define to the rescue … i basically have a “constants.php” that has all my defines, that i #include so that i always have access to them … here is the last iteration of the above code with define inline…
.
define("t","\t");
define("n","\n");
$list = '<ul>' . n;
$list .= t . '<li>one</li>' . n;
$list .= t . '<li>two</li>' . n;
$list .= t . '<li>three</li>' . n;
$list .= '<ul>' . n.n;
echo $list;
This may not look like much … but it saves some typing, and i think it’s much cleaner, plus with #include you can change things one place for certain constants… obviously TABS and NEWLINES probably won’t change but HTML snippets could…
Someone might say why not use local variables…
.
$t = "\t";
$n = "\n";
$list = '<ul>' . $n;
$list .= $t . '<li>one</li>' .$n;
$list .= $t . '<li>two</li>' . $n;
$list .= $t . '<li>three</li>' . $n;
$list .= '<ul>' . $n.$n;
echo $list;
One drawback of that is that variables are not accessible inside functions… where as constants are GLOBAL ...
Here is a snippet of my “constants.php” file …
"constants.php"
define("t","\t");
define("n","\n");
define("br","<br />");
define("brc",'<br clear="all" />');
define("sp"," ");
define("a","&");
define("vpipe",'<span class="vp"> | </span>');
define("r_arr",'»');
define("l_arr",'«');
define("req",' <span class="req">*</span>');