Monday 27 May 2013
Facebook StumbleUpon Twitter Google+ Pin It

PHP techniques I use all the time


Now I know that PHP isn't very "cool" these days; it's probably the most misunderstood web language because all the script kiddies use it to include files on their webpages and put up forms that get hacked hours later. But I think PHP deserves a whole lot more credit than it gets; it's fast, it integrates very nicely with Apache, it got all the right features in version 5, and even if you don't like using it, there's always a chance you might have to write some anyway. So, maybe these tips can help you out:
  • Use syntax for strings: If there's one thing I got tired of fast, it was building long strings like this:
    $s = "This is something ";
    $s .= "that will make ";
    $s .= "a long string, with ";
    $s .= "a variable: $x.";
    If I am going to make a string with more than one line, and even sometimes when I'm not, then I use heredoc. It's much, much cleaner than worrying about quotation marks, because it isn't delimited with them. Here's the same string as above, in one clean heredoc block:
    $s = <<<HEREDOC
      This is something 
      that will make 
      a long string, with 
      a variable: {$x}.
    HEREDOC;
    And, that delimiter can be anything; EOF, MYSTRING, ELEPHANT, etc. The only caveat is that the ending delimiter has to be all the way at the left; you can't put any spaces or tabs before it. This is a slight nuisance if you are serious about maintaining indentation, but it's a small compromise for having such a clean way of making strings.
  • Contain your variables in strings with curly braces. This goes along with the heredoc syntax above, but you can use it in double-quote delimited strings too. It looks like so:
    $x = "Something with {$y['key']} and {$z}.";
    It allows you to include array variables in strings and it makes the variables stand out better in most any text editor. Update 11/12: I should mention, for anyone who doesn't know, that using curly braces in your strings is not recommended when you are working with user input.  Either validate the user input to make sure that there are no curly braces before plugging it in, or don't use curly braces with user input at all.
  • Build arrays. Always. You probably won't make just one of something. Sooner or later, you'll realize you need two, and then you'll have to go back and turn that variable into an array so you can store multiple things. I walked into this mistake too many times… I would be processing a form, and have a variable called $errorto store a possible error, and then I realize 10 minutes later that there might be more than one error, and I need to make an array of errors, and I have to go back and rewrite things to use an array instead. Nowadays I don't get into that mess anymore; I just start with arrays and save myself the trouble.
  • Use associative arrays. (These are called hashes too.) They make things easier to keep track of. This goes along with the previous tip, though if you are just making a linear list of things, there's no need. Where associative arrays come in handy is when you need to remember the keys you use, because you can refer to the key with a variable. Say I have an array that I use to retrieve the address for a page, I can do the following (this is a horrible example though):
    $pages = array(
     'index' => 'startPage.php',
     'contact' => 'sendForm.php'
    );
     
    // could do some function here
    $thePage = 'contact';
     
    $theAddress = $pages[$thePage];
     
    // here I'll get sendForm.php
    I think that's very convenient.
  • Shortcut the else.
  • I learned this with C and I use it in PHP. What's the point of doing the following:
    if( this condition ) 
    {
      $x = 5; 
    }
    else 
    {
      $x = 10;
    }
    If the $x is going to be 10 by default, just start with 10. No need to bother typing the else at all. I just do this:
    $x = 10;
    if( this condition )
    {
      $x = 5;
    }
    And, that's all there is to it. It's a lot less typing.
  • Walk through arrays with foreach. Even arrays with numerical indexes. It's just way easier than worrying about a counter, figuring out the size of the array, etc. Even if I need a counter for any reason, I tend to useforeach anyway, and add a counter as if it were a while loop. Update 11/12: As Jon H mentioned, this is only for when you want to retrieve the data in an array, like when you are getting the results from a database query. If you need to modify the data in the array, then you can't use foreach should use this:
    $arr = array(0,1,2,3,4,5,6,7,8,9);
     
    foreach($arr as $key => $num) {
     if($num==5) {
      $arr[$key]=0;
     }
    }
    print_r($arr); 
    //5 got replaced to 0
    Thanks to Emilio for the tip!
  • Use switch, not a mess of if statements. It reads better, by far. Just don't forget your breaks:
    switch($x)
    {
     case 'one': ...; break; 
     case 'two': ...; break;
     default: ...; break;
    }
    You can also combine multiple cases, if you want them all to have the same result:
    case 'one': case 'two': ...; break;
  • Use clean syntax elements. Here are some simple things you can do to keep your code clean: Going to print a single variable? Just do:
    <?= $out ?>
    Don't like the ugly curly braces in your if-else statements? Just do:
    if( this condition ) : 
      ...
    else :
      ...
    endif;
    1
  • Process user input with a separate script. If a user is going to submit a form (and method='post' is always the way to go), then you should send it to a separate script that does all the work, then when it's done, send it off to a different script with:
    header('Location: ' . $url);
    … where the actual $url can be relative or absolute. This way, the user can't hit refresh and post the data all over again, which is annoying, and you can send the user off to different scripts depending on the outcome of the processing. Update: Andrew made a good point in the comments about reporting errors back to the user, which totally slipped my mind. I might write up something soon about a better way to handle forms.
  • Follow a strict order in your scripts. Even if you are just writing very simple functional code, it pays to have some order. If you are going to do everything in one file, try to follow something like this:
    1. Process user input.
    2. Query databases.
    3. Build and process all data, make arrays, strings, etc.
    4. Display everything, don't do any more processing or retrieving in the markup!
    Then, when you have to go back and change things, it's easy to remember where to look for, say, database queries. They will always be in the same relative part of your scripts.
  • Be consistent. This is the best piece of advice I can give. Just because occasionally you can cut corners, like writing an if statement without the curly braces because you only need one line, that doesn't mean you should do it. Code is easiest to read when you are consistent about the way you do things, regardless of the exact way you decide on, and when you develop a habit for writing things one way, you reduce the chance of making stupid typos down the road, because you'll have the correct method engraved into your head.
That's my list; if I think of more things, I'll share them. In the meantime, share your PHP techniques, I would be very glad to hear them!

No comments: