Tips for writing compact PHP code

Posted on March 25, 2009

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:

1
2
3
4
5
6
7
8
if ( $module == TRUE )
{
    load($module);
}
else
{
    error('No module');
}

Short:

1
2
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:

1
2
3
4
5
6
7
8
if ( $foo )
{
   echo $foo;
}
else
{
   echo $bar;
}

Short:

1
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:

1
2
3
4
5
6
7
8
9
10
11
function has_value($var)
{
    if ( $var == TRUE )
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}

Short:

1
2
3
4
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:

1
2
3
4
5
6
7
8
if ( $foo > 3 )
{
    $message = '$foo is greater then 3.';
}
else
{
    $message = '$foo is lower than or equal to 3.';
}

Short:

1
2
3
4
5
6
$message = '$foo is lower than or equal to 3.';
 
if ( $foo > 3 )
{
    $message = '$foo is greater then 3.';
}

6. Assign variables inside conditions

Long:

1
2
3
4
5
6
$contents = file_get_contents($file);
 
if ( $contents )
{
    echo $contents;
}

Short:

1
2
3
4
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:

1
2
3
4
5
class db
{
    public $query;
    public $result;
    public $tables;

Short:

1
2
3
4
5
6
7
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:

1
2
3
$foo    = TRUE;
$bar    = TRUE;
$foobar = TRUE;

Short:

1
2
3
$foo    =
$bar    =
$foobar = TRUE;

8. Merge arrays instead of assigning individual keys

Long:

1
2
3
4
5
$items = array('item 1', 'item 2');
 
$items[] = 'item 3';
$items[] = 'item 4';
$items[] = 'item 5';

Short:

1
2
3
4
5
6
7
$items = array('item 1', 'item 2');
 
$items = array_merge($items, array(
    'item 3',
    'item 4',
    'item 5'
    ));

Even shorter:

1
2
3
4
5
6
7
$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.

Scroll to top

Comments (5)

  • These are some pretty interesting tips, didn't know of some they would actually work. But understand that this doesn't make understanding the code more easy in some cases. 7. for example, when an inexperienced programmer tries to change the value of $bar, this could happen:
    $foo =
    $bar = false
    $foobar = true;

    But thanks for the tips, because they definitely are usefull!

    Posted by Rik on March 25, 2009 Reply

  • I'm with Rik, while these are all perfectly capable of making your code more compact there is literally no reason to do so. The goal of good code is to be readable, and while I think most of the tips are perfectly acceptable it might make it harder for someone not as experienced to figure out what's going on.

    Though I would like to point out that certain ways of coding are actually faster/more efficient, for instance in example 8 using the code this way..

    $variable[] = “value1”;
    $variable[] = “value2”;

    is slower than doing…

    $variable ( 'value1', 'value2' );

    Also one tip for writing more readable code is by using switch statements, long if else statements can get messy, use a switch to make it easy and readable

    Posted by Abi on March 25, 2009 Reply

  • Great article, although I think that some tips aren't working for me. But most of it should help me to compress the length of my codings. Great blog btw, congrats! I hope to read more from you!

    Posted by CoenJacobs on March 25, 2009 Reply

  • Agree, simply write them in 1 line. $foo = $bar = $foobar = false;
    Great article Elbert.

    Posted by svenn on April 04, 2009 Reply

  • Syntax itself can make things shorter.

    if (condition)
    {
    do something;
    }
    else
    {
    do something else;
    }

    is 8 lines, while

    if (condition) {
    do something;
    } else {
    do somerhing else;
    }

    is only 5 lines and more readable to me

    Posted by Ozh on April 14, 2009 Reply

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> <pre lang="" line="" escaped="" highlight="">

Fork me on GitHub