Website Speed Part 4 : PHP Programming for Speed

Programming for speed is not what most coders think of. What they tend to consider first, and usually only, is getting it working. Sometimes people will talk of refactoring to reduce the amount of code, but again this is usually only for those that suffer with the luxury of having too much money and time.

I wish I had that luxury, to be able to spend twice as long on a problem to make a perfect solution. In truth I don’t most of the time, as I am out there getting new clients, making other products or not in the fortunate position to have a client with very deep pockets.

To counteract these things I have a bunch of methods stored in my head that allow me to choose the best path first time (I hope!). I am going to share these best practices with you so you can maybe do the same, maybe even better. If you have any great speed suggestions for coding, please comment and I will append it to this post.

Also, please note that this is not an exhaustive list. This is more of a pointer to things you should consider in your favorite coding language. Although this is for PHP specifically, I’ve tried to keep it as generic as possible to make it possible for all coders, no matter the language, to benefit.

Making IF ELSE smaller

IF is possibly the most used statement from all the programming languages, and I think the most used by a noob programmer (hey I was one once, I remember my code).

Common IF ELSE usage

          if ( $something == true ){
              $value = 'yes';
              $value = 'no';

Now using only IF

          $value = 'no';
          if ( $something == true ){
              $value = 'yes';

As you can see all that has been done is that value is pre-set to ‘no’ and only gets changed to ‘yes’ if something is true. Both bits of code have the same outcome, one has less code.

If you only have 1 command inside the if statement then you can take things a little further. PHP does not require that you have the curly brackets when there is just one line.

          $value = 'no';
          if ( $something == true )
              $value = 'yes';

Ternary operators

We can go a stage further and have Ternary Operators. These are mathematical instructions that allow for a yes/no answer, just like IF.

IF presented as ternary operation

          $value = ( $something == true ) ? "yes" : "no" ;

Again the same IF ELSE statement, made much smaller. What it does is check the if the statement inside the brackets is either true or false, if it is true it will set value to be “yes”, if it is false it will set value to be “no”

syntax of ternary operators

          output = ( true/false condition ) ? true-value : false-value ;

It is not essential to have an output, as the true or false value could call a function and not return a value.

Using Range to create an array of numbers

Often people will code an array with just a bunch of numbers in it so that they can loop through it.

PHP code to create a select drop down list

          // selected item value
          $item = 12;
          // create array of numbers
          $array_of_numbers = array( 2,4,6,8,10,12,14,16 );
          // start the select 
          echo "<select name='myselect' >";
          foreach ($array_of_numbers as $number){
          // use terany operator to compare $number and $item, if the same make $selected = "selected"
          $selected = ( $number == $item ) ? "selected" : "" ;
          // echo option, with details filled in
          echo "<option value='" . $number . "' " . $selected . " >" . $number . "</option>";
          echo "</select>";

Now the same thing shorter with range

          // selected item value
          $item = 12;
          // start the select
          echo "<select name='myselect' >";
          foreach ( range(2,16,2) as $number){
          // use ternary operator to compare $number and $item, if the same make $selected = "selected"
          $selected = ( $number == $item ) ? "selected" : "" ;
          // echo option, with details filled in
          echo "<option value='" . $number . "' " . $selected . " >" . $number . "</option>";
          echo "</select>";

Range is a really handy thing, as what it does is created an array of numbers (integers). It has the following syntax in php:

          range($start_number, $end_number, $increment);

The only needed compulsory items are the start and end number, the increment defaults to 1, but can be any number you like.

A range function is available in most languages but is unfortunately not available in Javascript out of the box, so to make this same saving in code you would be best to use a FOR loop

FOR loop version

          // selected item value
          $item = 12;
          // start the select
          echo "<select name='myselect' >";
          for($number = 2; $number <= 16; $number = $number + 2){
          // use ternary operator to compare $number and $item, if the same make $selected = "selected"
          $selected = ( $number == $item ) ? "selected" : "" ;
          // echo option, with
          echo "<option value='" . $number . "' " . $selected . " >" . $number . "</option>";
          echo "</select>";

Turbo charging the FOR loop

Many people like to use a for loop as they believe that it is faster than a foreach. While this is often true, it does not offer the flexibility of foreach and with the wrong programming techniques can be slower

The slower FOR loop

            // some text as a string
            $text="We love SpeckyBoy";
            // loop through all the characters
            for($i=0; $i < strlen($text); $i++){
                // look for the o in the text string at the position of $i using a ternary operator
                // echo true or false value as needed
                echo ( substr($text,$i,1) == 'o' ) ? "its an o" : "no o here";

The faster FOR loop

            // some text as a string
            $text="We love SpeckyBoy";
            // get the length of the string
            $length = strlen($text);
            // loop through all the characters
            for($i=0; $i < $length ; $i++){
                // look for the o in the text string at the position of $i using a ternary operator
                // echo true or false value as needed
                echo ( substr($text,$i,1) == 'o' ) ? "its an o" : "no o here";

The 2nd for loop is faster as it does not need to re-check the string length each time the loop runs. The first loop will check the string length 17 times with the text used

Making your code easier to maintain, and faster

I often see the same problem with my noob code when I re-visit it. The code is all written on 1 line and very long. Check this bit of code as an example:

          $html = "<input name='" . $name . "' id='" . $id . "' value='" . $value . "' class='" . $theclass . "' type='checkbox' " . $checked . " />";
          echo $html;

It works just fine, and will be ok for any implementation, but there are some problems with it. For example if the class is empty, it is wasteful to code the empty class setting. While this may not make so much difference to a Javascript implementation, as this is being generated on the server with PHP, you’d be sending extra bytes to the clients browser which are not required. This of course will make the most difference when making AJAX calls and waiting for the reply, where extra bytes can make much more of an impact.

An easier way to maintain

          $attributes = " name='" . $name  . "' ";
          $attributes .= " id='" . $id  . "' ";
          $attributes .= " value='" . $value  . "' ";
          $attributes .= ($theclass != '' )?  " class='" . $theclass  . "' " : "" ;
          $attributes .= ($selected == $value )?  " checked " : "" ;
          $html = "<input type='checkbox' " . $attributes  . " />";
          echo $html;

As you can see, much easier to read, much easier to maintain, and used on the server side will produce less HTML code.

Don’t echo every line only the final output

It’s much easier to echo every line, or pass control back to HTML, than it is to write every line to a variable, yet writing the output to a variable first and only echoing at the end is the faster way to process

The easy way to do things, with a few variations

    echo "<h2>" . $title . "</h2>"; ?>
    <small><?php echo date(); ?><small>

The more server friendly way to do things

    $output = "<h2>" . $title . "</h2>";
    $output .= "<small>" . date() . "<small>";
    echo $output;

OK, this is a very simplistic example of what you should do as it is only 2 lines and then output.

Rounding up

This is a very short list of things to help make your PHP coding faster and easier to maintain. There is of course many more things that you can do to reduce the amount of code that you do use, or the speed that it runs at.

Most of these techniques can be taken across to other programming languages, so when your coding in Javascript or .NET give it some thought and you will be making things much faster.

More from the Website Speed series…

Website Speed Part 1: Write More Efficient CSS →
Website Speed Part 2: Working With and Optimizing Images for the Web →
Website Speed Part 3 – Caching WordPress →


  • As is always the case, thanks Andy. 

    The best one for me was “Turbo charging the FOR loop” because it exemplifies the rule “It’s not just what you do but when you do it.” With this in mind efficient code becomes a do it right the first time effort and not something for after the fact.

    btw, do you think you might be able to add a bit about using If /else vs switch/case?

  • As far as i remeber its the “ternary” operator :D

  • It’s worth noting a couple of things – mainly that most of these aren’t actually quicker, other than to type.

    It’s also worth noting That strings that have ” round then can contain variables, so you don’t need to concatenate with the dot all the time. If the variable is complex, then wrapping it in {} will ensure it works.

    Heredocs are quite nice for that sort of thing as well, as they don’t need escaping.

    Seem of this stuff, like dropping the {} on conditional statements with one line is quite bad advice, that particular often causes bugs if you later add more indented lines without realising you’ve missed the {}.

    There isn’t any reason to write concise PHP at the expense of clarity.

  • Andy

    At least I was consistent with my bad spelling!  thanks for the pointer of the missing r, all fixed now.

  • Chris

    Genuinely wondering (because I don’t know the answer myself!), but is the IF/ELSE example actually quicker? More code doesn’t necessarily mean slower code does it? In your example you go from doing a bool check and then setting a value based on the result, to setting a value, doing a bool check and potentially setting another value.

  • agentursimon

    Chapter “Making your code easier to maintain, and faster”

    It is easier and faster to work with sprintf:

      $html = "";  echo sprintf($html,    $name,    $id,    $value,    $theclass,    ($selected == $value )?  " checked " : "" ,    $attributes); 

  • Andy

    personally I find sprintf to be slightly more annoying to use as you have to remember what the variables will be, interger, string etc and get them in the same order in the code.  Can be very annoying and long when dealing with many “attributes”, with much less room for error.  

    But hey, that said,  if your happy with sprintf, then do go for it.  :)

  • Andy

    Chirs, the idea of the example code was to make something as simple as possible to understand for the masses, not necessarily the best code.  it’s more conceptual than actual.

    it could have been written 
    $value = ‘no’;
           $value = ‘yes’

    and value could be used as a string later… etc…. 

    However I do dig your point.

    From the simple php testing I’ve done before yes setting the variable first and only re-setting it if the IF is ‘true’ is marginally quicker. It is for sure quicker on javascript to do it this way as less code is important there…


  • Andy

    do disagree with you on the first point that they are just shorter to type.  Even with a shorter to type php implementation it will be faster than longer more verbose implementations…less memory usage for example.  

    I might add a section at the end to deal with {}  for variables, was always told to do the . variable .  way for readability

    I agree that if without the {} can be annoying. 

  • Pushpinder Bagga

    Nice thing you folks told people about Ternary operators and Range. Cheers!

  • Some of these suggestions look like premature optimisation… if you’re dealing with a small amount of code that has to be run as fast as possible, then fair enough. But with larger amounts of code eg. inside a CMS there are typically far greater gains to be made at a structural level that should be investigated first.
    I can strongly recommend the use of PHP profiling as a starting point, to see where the bottlenecks are. These are typically found in things like unneeded plugins for the CMS, tight loops that you’d forgotten about, or unoptimised/unnecessary/uncached database queries.

    Once you’ve found these, spend your effort on removing these bottlenecks, optimising your tight loops to death, whatever, then work out from there. In my opinion, the rest of your code should be written for clarity over tiny optimisations. Most PHP code that’s run once per page request is not going to yield more than a few milliseconds in total by optimisation. Something in a loop run 10000 times has 10000 times the payoff if you optimise it.

  • yaonice

    These are very useful ! THX

  • Anon


  • Hhendrady

    Hey it was nice post.. i learn a lot. thanks mate.. Website Speed Awesome !!!

  • Andy

    actually on second thoughts I will spend the time to add this suggestion to the end of the post as at the beginning I said I would.  would be rude not to stand up to my word.  thanks for the pointer. 

  • Torinski

    Still it depends on how many times the statement can become True. So it is not quicker all the time.
    As always with this kind of micro optimisation, it should really be done if your application really needs you to spend a lot of time checking the performance of these kind of things.

  • Jérémy DERUSSÉ

    Please, avoid to manipulate string :
    $attributes = ” name='” . $name  . “‘ “;$attributes .= ” id='” . $id  . “‘ “;$attributes .= ” value='” . $value  . “‘ “;$attributes .= ($theclass != ” )?  ” class='” . $theclass  . “‘ ” : “” ;$attributes .= ($selected == $value )?  ” checked ” : “” ;$html = “”;echo $html;

    Each time you assign a new value to the variable, the memory, is copyied.
    An other clear way : 
    $attributes = ” name='” . $name  . “‘ ” . ” id='” . $id  . “‘ ” . ” value='” . $value  . “‘ ” . ($theclass != ” )?  ” class='” . $theclass  . “‘ ” : “” . ($selected == $value )?  ” checked ” : “” ;$html = “”;echo $html;Or with array$attributes = array(
    “name='” . $name  . “‘ “,
    “id='” . $id  . “‘ “,
    “value='” . $value  . “‘ “,
    ($theclass != ” )?  “class='” . $theclass  . “‘ ” : “”,
    ($selected == $value )?  “checked ” : “”
    $html = “”;
    echo $html;

  • $class = ( !empty( $theclass ) ) ?  ‘ class=”‘ . $theclass  . ‘” ‘ : ”;
    $checked = ( $selected === $value ) ?  ‘ checked=”checked” ‘ : ”;
    $input = sprintf( ”, $name, $id, $value, $class, $checked );
    echo $input;

    My balance code between speed and clarty ! What do you think about it ?

  • Harry

    Awesome  Post i like it

  • Great post. I love it. I will definitely use the tips to speed up my PHP project.

  • Great read! Learnt many handy tips here. :)

  • Tio nélio Do Rincão

    tks tks brow
    hugs from brazil