Tips for writing compact PHP code
Writing compact code can save you time. It’s not always recommended and often even strongly discouraged as it makes your code less readable, but for simple operations it can be more efficient. In this post I will give a few examples.
1. Drop braces
Braces aren’t required in control structures with only one expression. Sometimes it makes sense to drop them. It’s very easy to make mistakes if you ever add code to the structure, I recommend only to do this when the expression is short and fits on a single line.
Long:
if ( $module == TRUE ) { load($module); } else { error('No module'); }
Short:
if ( $module ) load($module); else error('No module');
2. Use ternary operators
The above example can be made even more compact using ternary operators:
$module ? load($module) : error('No module');
3. Use “OR” instead of “IF”
“OR” is the same as “or” and ”||”.
Long:
if ( $foo ) { echo $foo; } else { echo $bar; }
Short:
echo $foo || $bar;
4. Don’t compare variables to booleans
“if ( $foo == TRUE )” is the same as “if ( $foo )”. This shortcut can make your life as a programmer much easier:
Long:
function has_value($var) { if ( $var == TRUE ) { return TRUE; } else { return FALSE; } }
Short:
function has_value($var) { return ( bool ) $var; }
5. Use default values for variables
It’s usually a good idea to define important variables at the beginning of your script, instead of inside control structures (this could result in undefined variables later on). Another advantage is that you can often save an entire else-block as demonstrated in this example:
Long:
if ( $foo > 3 ) { $message = '$foo is greater then 3.'; } else { $message = '$foo is lower than or equal to 3.'; }
Short:
$message = '$foo is lower than or equal to 3.'; if ( $foo > 3 ) { $message = '$foo is greater then 3.'; }
6. Assign variables inside conditions
Long:
$contents = file_get_contents($file); if ( $contents ) { echo $contents; }
Short:
if ( $contents = file_get_contents($file) ) { echo $contents; }
7. Group variable declarations
Instead of prefixing every single variable declaration in a class with “public”, “protected” or “private” keywords, group them:
Long:
class db { public $query; public $result; public $tables;
Short:
class db { public $query, $result, $tables ;
Something similar can be done with regular variable declarations if they need to assign them the same value:
Long:
$foo = TRUE; $bar = TRUE; $foobar = TRUE;
Short:
$foo = $bar = $foobar = TRUE;
8. Merge arrays instead of assigning individual keys
Long:
$items = array('item 1', 'item 2'); $items[] = 'item 3'; $items[] = 'item 4'; $items[] = 'item 5';
Short:
$items = array('item 1', 'item 2'); $items = array_merge($items, array( 'item 3', 'item 4', 'item 5' ));
Even shorter:
$items = array('item 1', 'item 2'); $items += array( 'item 3', 'item 4', 'item 5' );
That’s it! Please share this post if you found it useful.
Filed under Programming