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.
- 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
- 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>';
- 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 toecho $varOne . $varTwo . $varThree;. It’s faster because echo outputs each variable seperately instead of concatenating the variables and then outputting them as one. - 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 includedor die();Use the @ sign to fix this.@mysql_connect( $user... );won’t show any nasty MySQL connection errors to the user. - 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.