5 Simple PHP Tricks

Learn a few PHP programming tricks to make your code cleaner and better. A few of these are just for fun, but a few could actually help you in a development situation.

  1. Leave out the closing ?> tag. The closing tag the end of a PHP document is unecessary, and it can create problems when you are dealing with uneeded whitespace. You can just omit it. Example:
    <?php
    
    	// some code here
    
    ?>
    
    You can even jump out of PHP for a second.
    
    <?php
    
    	// some more code
    
  2. Use <pre> tags when you print_r();. Every time I needed a quick idea of what was in an Array, I would just print_r(), and then View > Source of the document. This would give me the formatted array output that I wanted, not the ball of text given by viewing the website normally. I learned that I can just use <pre> tags to make the print_r() appear normally. Example:
    echo '<pre>';
    
    print_r( $array );
    
    echo '< /pre>';
    
  3. The language construct echo accepts more than one parameter. It’s also faster when you use this. You can call: echo $varOne, $varTwo, $varThree; as opposed to echo $varOne . $varTwo . $varThree;. It’s faster because echo outputs each variable seperately instead of concatenating the variables and then outputting them as one.
  4. Use the @ sign to omit errors. This is already known by a lot, but for those who don’t know it it should be here. If you call the function mysql_connect( $user... ); you could end up showing the user a bunch of errors, even if you included or die(); Use the @ sign to fix this. @mysql_connect( $user... ); won’t show any nasty MySQL connection errors to the user.
  5. Use shorthand code. Shorthand code and significantly shorten the length of your code, and for some people it makes the code easier to understand. If you are working on a project alone, or with a team, you should decide whether to use this everywhere or no where. Instead of writing the code:
    if( !empty( $array['key'] ) ) {
    
    	$variable = $array['key'];
    
    } else {
    
    	$variable = 'Not found';
    
    }

    You could write the code:

    $variable = !empty( $array['key'] ) ? $array['key'] : 'Not found';

    For some this is easier to understand. You can just look across the line and see conditions ? action if true : action if false;

Have your own PHP tricks? Share them! Leave a comment using the form below.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>