ucantblamem

My top 5 PHP tips and tricks

7th Dec 2007

As we grow up we expand our vocabulary more and more. In fact, we will keep learning until the day we die, as not many of us will ever have a firm grasp on every word in our native tongue.

This fact very much applies to programmers, especially web-developers, who have to learn multiple languages to get anything done. This makes it very hard for us to truly master any one single language.

Even though I’ve only been developing in PHP for around 5 years, I have come to learn a few little tricks that I wish someone had taught me way back in the beginning. One, some or more of these may be old news to you, but I hope someone finds them helpful. Oh and feel free to chime in if you would like to add to this (very small) list.

Omitting the final ‘?>’

This probably doesn’t need too much explanation, except to say that the very last closing PHP tag in a document can be left off. The PHP parser has to do extra work every time you open and/or close a PHP tag and if you’re like me and keep your logic separate from your views, this makes processing controllers and models just that little bit faster.

It also inadvertently solves a lot of issues with white space causing “Headers already sent” errors.

++$i not $i++

There are a lot of good articles about PHP performance, but this little trick is one of my favourite. When you’re incrementing a variable (in a for() loop for instance) you should put the increment operator before the variable rather that after. I don’t know the exact figure, but it’s said to be something like 7 times faster in processing time!

if ($var) {}

PHP is a dynamically typed language, which means we can do some pretty funky stuff with variables, but my favourite aspect of dynamic typing is what can be done when testing a variable in a condition.

Let’s take a look at some code:

$empty_string = '';
$zero_value = 0;
$false_bool = false;

if ($empty_string || $zero_value || $false_bool) {
    // this will never be run, because all these variables equate to false
}

This is because an empty string or a zero value equate to false. So, for instance instead of coding:

if (count($my_array) == 0) {
}

We can simply type:

if (!count($my_array)) {
}

Of course, as usual php.net has great documentation on this very thing.

Type casting

One of my other favourite things about the PHP syntax is type casting. Because it is a dynamically typed language, sometimes you just want to force a variable to be a particular type. This can be achieved with type casting.

A great example of this is when you want to pull an ID number from the URL and throw it to an SQL statement; we don’t need characters in the ID and in fact, we don’t want characters, as they could very well be an SQL injection attack. The easiest way to ensure we get a clean ID is to cast the variable to an integer like so:

$id = $_GET['id'];
$sql =  ‘SELECT * FROM `my_table` WHERE id =  ‘. (int) $id;

The (int) is the cast, just in case you missed it. But, that’s not all folks! We can cast compound types as well. I’m a big fan of objects and whenever I do a database call, I like my results to come back as objects, but sometimes you need an associative array for things. PHP provides us with an (object) cast and an (array) cast, which we can actually use conversely on objects and arrays:

$obj = new stdClass;
$obj->name = 'James';
$obj->job = 'Professional nerd';

$array = (array) $obj;

// $array now equals this:
// Array
// (
//     [name] => James
//     [job] => Professional nerd
// )

Not bad huh?

Alternative syntax for control structures

As stated earlier, I’m a bit of an MVC fan, so I like good separation of logic and views, which helps tonnes with maintainability and debugging. One of the things I like to do to help my eyes quickly distinguish between a Controller/Model and a View is to use PHP’s alternative syntax for control structures. So, where I might ordinarily do this:

<ul>
    <?php foreach ($links as $link) { ?>
    <li><?php echo $link; ></li>
    <?php } ?>
</ul>

I can instead do this:

<ul>
    <?php foreach ($links as $link): ?>
    <li><?php echo $link; ></li>
    <?php endforeach; ?>
</ul>

I personally find that on large chunks of view my eyes find it easier to spot the endforeach; than a closing curly-bracket.

One Response to “My top 5 PHP tips and tricks”

  1. Lee Haskings Lee Haskings Says:

    Nice little set of tips there - that ‘++$i’ is a new on for me which Ill try and remember for future work!

    On the topic of the ‘if ($var) {}’ tip (which you mentioned to me last time we met) I have to give a warning to people that this only works with variables and NOT defines such as when generated by:

    define (’define_name’, ‘define_value’);

    If you have NOT SET the define then the following will be true:

    As ‘define_name’ will equate to ‘define_name’. To solve this make sure for any defines that you use:

    To check a define/constant has been set.

Leave a Reply