16 Sept 2013

PHP Useful techniques :You Need To Know


PHP is not very "cool" these days; it's in all probability the foremost misunderstood web language as a result of all the script kiddies use it to include files on their webpages and place up forms that get hacked hours later. however i feel PHP deserves an entire ton a lot of credit than it gets; it's quick, it integrates terribly nicely with Apache, it got all the proper features in version 5, and even if you do not like using it, there is always an opportunity you may have to write some anyway. So, perhaps the following tips will assist you out:



Use heredoc syntax for strings: If there is one factor I got uninterested in quick, it had been building long strings like this:
                   $s = "This is something ";
                      $s .= "that will make ";
                      $s .= "a long string, with ";
                      $s .= "a variable: $x.";
If i'm getting to build a string with quite one line, and even typically once i am not, then i use heredoc. It's much, a lot of cleaner than worrying about quotation marks, because it's not delimited with them. Here's an equivalent string as on top of, in one clean heredoc block:
                       $s=<<
                       This is something that
                       will make a long string,
                       with a variable: {$x}. 
                       HEREDOC
And, that delimiter is anything; EOF, MYSTRING, ELEPHANT, etc. the only caveat is that the ending delimiter needs to be all the way at the left; you cannot place any spaces or tabs before it. this can be a small nuisance if you're serious regarding maintaining indentation, however it is a little compromise for having such a clean manner of constructing strings. 

  • Contain your variables in strings with curly braces. This goes together with the heredoc syntax above, however you can use it in double-quote delimited strings too. it's like so:
                         $x = "Something with {$y['key']} and {$z}.";

It permits you to incorporate array variables in strings and it makes the variables stand out better in most any text editor. Update 11/12: I ought to mention, for anyone who does not know, that using curled braces in your strings isn't suggested once you working operating with user input. See this bug. Either validate the user input to form certain that there aren't any curled braces before plugging it in, or do not use curled braces with user input in any respect. 
  • Build arrays. Always. you almost certainly will not create only 1 of one thing. Sooner or later, you will understand you wish two, therefore} you'll need to travel back and switch that variable into an array so you'll store multiple things. I walked into this error too several times… i'd be process a kind, and have a variable known as $error to store a possible error, and so I understand ten minutes later that there may be over one error, and that i got to create an array of errors, and that i need to return and rewrite things to use an array instead. today i do not get into that mess anymore; I simply begin with arrays and save myself the difficulty. 
  • Use associative arrays. (These ar known as hashes too.) they create things easier to stay track of. This goes along side the previous tip, tho' if you're simply creating a linear list of things, there is not any want. wherever associative arrays come in handy is once you got to bear in mind the keys you utilize, as a result of you'll refer to the key with a variable. Say I actually have an array that i take advantage of to retrieve the address for a page, I will do the subsequent (this may be a alarming 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.
                          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;
                          }
  • Walk through arrays with foreach. Even arrays with numerical indexes. It's simply means easier than worrying about a counter, deciding the scale of the array, etc. even if i want a counter for any reason, I tend to use foreach anyway, and add a counter as if it were a while loop. Update 11/12: As Jon H mentioned, this is often only for when you want to retrieve the data in an array, like once you are getting the results from a database query. If you wish to change the data within the array, then you cannot 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

  • Follow a strict order in your scripts. even if you're simply writing terribly easy useful code, it pays to possess some order. If you're aiming to do everything in one file, attempt to follow something like this:

   1.Process user input.

   2.Query databases.
   3.Build and method all information, build arrays, strings, etc.
   4.Display everything, do not do to any extent further process or retrieving within the    markup!
Then, once you ought to return and alter things, it is easy to recollect wherever to appear for, say, database queries. they're going to always be within the same relative a part of your scripts.

No comments:

Post a Comment