These Things I Know, PHP Tips » 荒野无灯weblog

Keep It Simple, Stupid.


These Things I Know, PHP Tips

There is more than one way to achieve the same result when programming in PHP. There are many shortcuts I wish someone had explained to me when I began learning the language. (One would assume that is what those $49.99 books are for, but apparently there are only written to bewilder the reader into buying another book.)

It All Adds Up

$variable = $variable + 1;

Is the same as:

$variable ++;

This method also works for subtraction:

$variable --;

You can also apply a similar method for concocting strings. So instead of:

$mytext = 'Done and Done.';
$mytext = "$mytext And I mean Done!"; // $mytext = 'Done and Done And I mean Done!';

Use this shorthand method of adding another string of text onto the end of the first string:

$mytext = 'Done and Done.';
$mytext .= ' And I mean Done!'; // $mytext = 'Done and Done And I mean Done!';

Single Quotes versus Double Quotes

Any time you put something in “double” quotes, you are asking PHP to check that content for a variable. So even though the following lines do not contain variables within the double quotes, PHP will still waste precious computing time scanning them anyway.

$mytext = "Dental Plan";
if ($mytext == "Dental Plan") {
echo "Lisa needs braces"; }

Those same three lines of code could be executed much faster if ‘single’ quotes were used in place of “double” quotes.

$mytext = 'Dental Plan';
if ($mytext == 'Dental Plan') {
echo 'Lisa needs braces'; }

Now that may not seem like much, but having PHP check for variables where it doesn’t need to over the course of a larger script, can certainly impede run-time. Just to clarify my point, PHP will not read a variable if it is within ‘single’ quotes.

echo '$mytext, Lisa needs braces.';
// Will output: $mytext, Lisa needs braces.
echo "$mytext, Lisa needs braces.";
// Will output: Dental Plan, Lisa needs braces.

What is the the super-secret of keeping those scripts speeding along the rusty pipes of your server? Avoid double quotes at all costs. Even if you are working with a variable and think you need double quotes, it is more efficient for PHP to execute this:

echo $mytext . 'Lisa needs braces.';

As opposed to this bit of molasses-like code:

echo "$mytext Lisa needs braces.";

One control structure to rule them all, One constant to find them, One set of conditional brackets to bring them all and in the darkness bind them

Not anymore! If you have a single expression following a control structure, you do not need to waste your time with brackets { }.

if ($gollum == 'halfling') {
$height --;

Is the same as:

if ($gollum == 'halfling') $height --;

This can be applied to any control structure statement. For example:

if ($gollum == 'halfling') $height --;
else $height ++;

if ($frodo != 'dead')
echo 'Gosh darnit, roll again Sauron';

foreach ($kill as $count)
echo 'Legolas strikes again, that makes' . $count . 'for me!';

The fewer brackets you have cluttering up your code, the easier it may be to read.

They true did false, they were the trueiest bunch of falses that ever trued

If all you are trying to test for is a boolean (true/false) of a variable or function then instead of laying down a bunch of code like this:

if ($blackbeard == true) echo 'Arr, this chair be high, says I.';
elseif ($seacaptain == false) echo 'Yar, I'm not attractive.';

You can omit == and != with:

if ($blackbeard) echo 'Arr, this chair be high, says I.';
elseif (!$seacaptain) echo 'Yar, I'm not attractive.';

This same format can apply to functions and multiple conditions. For example:

if ($benedict_arnold != true && strpos($photo,'map') == true)
echo 'You idiot, you can't read!';

if (high_chair($blackbeard) == false)
echo 'Aye, 'tis true. My debauchery was my way of compensating.';

The following is the same exact statement (except with less code):

if (!$benedict_arnold && strpos($photo,'map'))
echo 'You idiot, you can't read!';

if (!high_chair($blackbeard))
echo 'Aye, 'tis true. My debauchery was my way of compensating.';

In and out of PHP before they even knew what hit ‘em

When embedding PHP within HTML, you can close your PHP tag whenever you want to output HTML. This enables speedier processing of your PHP. For instance:

<?php if($bush_sewer) { ?>

<div class='neighbor'>
<strong>Hey Turkeys! Behind ya!</strong>

<?php } elseif (street($gorbachev)) { ?>

<div class='russian'>
<i>I just drop by with present for warming of house, instead find you grappling with <?php echo $local_oaf ?></i>



$name = 'Stu';
echo 'Disco' . $name . 'doesn't advertise...'; ?>

Hopefully that last one didn’t confuse you as much it confused me, the example is a bit extreme. However look over it a few times and you will understand exactly what is going on.

A few more for the road…

  1. Don’t use spaces to format your code, use tabs. Every space takes up 1 byte, every tab takes up 1 byte too. So if you are using 4 spaces to make 1 tab, you will have added unnecessary bulk (and CPU time) to your code.
  2. Learn Regular Expressions, which are beyond the scope of this article. However once mastered, you will transform into an unstoppable coder of such power that even your own expertise of regular expressions cannot calculate your might.
  3. If you are dealing with external variables through get/post. Always use $_POST['variable'] or $_GET['variable']. Assuming $variable can open a huge security hole into your script. With the upgrade to PHP5, register_globals is turned off, by default – so scripts will be forced to use the above method.

    Here is a code snippet to quickly gather $_GET and $_POST variables:

    // $_POST['form_name'] = 'Anus Mcgee';

    foreach ($_POST as $key => $value)
    $$key = $value;

    // Now $form_name = 'Anus Mcgee';

PHP Links and Resources

Hopefully a few of the examples I have demonstrated have made you hit yourself on the head and say – “I wish I had known that before!” I think each one had that effect on me.

Nick got hooked into the whole web fad back in the summer of 99′. Come snow-fall, he had his own domain name and a firm grasp of HTML. It all just kind of snowballed from there as the content and complexity on his first site began to multiply. By the winter of 2000 he was sick of the internet. Nick wasn’t on the web to write articles and feed substance to the masses. He was there to offend people, make neat shit, and look at porn.

Nick maintains a weblog about bikes, music and bullshit: 53×

another tip:

Submitted by jadwigo on November 2, 2005 – 17:30.

another tip:

if you need to output a lot of small strings, first make them into one string.

echo 'string one';
'string two';
'string three';
'string four';
'string five';

is much slower than

= 'string one';
$output .= 'string two';
$output .= 'string three';
$output .= 'string four';
$output .= 'string five';

Though I prefer the print() and printf() functions over echo.

One negative mark about strings enclosed in single quotes is that you cannot use special control characters like \n, \r and \t inside them, if you want to format your code / output an email body you’ll need a string enclosed in double quotes. I never noticed any speed difference, and vaguely remember someone actually testing the speed difference who found the impact negligable.

Tagged in :

All Comments (1)
Gravatar image
Gravatar image
porn sex binary
porn sex binary