PHP programming shortcuts: save time and lines of useless code.

Before I even started writing this, I am sure that the comments will be filled about how consolidating code makes it hard to understand, more braces makes it easier to read, etc. This is for those who think it’s better to have less code, such as yours truly. I like seeing less code; I find it more efficient and much better.

Short-hand mathematical operators
Those are known by most programmers however missed by a lot, the following can be shortened by it’s alternative next to it.

$int1 = $int1 + $int2; -- or alternatively: $int += $int2;
$int1 = $int1 - $int2; -- or alternatively: $int -= $int2;
$int1 = $int1 * $int2; -- or alternatively: $int *= $int2;
$int1 = $int1 / $int2; -- or alternatively: $int /= $int2;

Counters
Here is another very simple one, but good to know for those who don’t know about it.

$int = $int + 1; -- or alternatively: $int++;
$int = $int – 1; -- or alternatively: $int--;

Short-hand print statements
Ever find yourself have to write so much just to be able to echo a variable in HTML? No more!

<?php echo $string; ?> -- or alternatively, <?=$string?>

Braces: you don’t always need them.
You don’t always need to use the braces in any if or while statement if it only containers one directive.

if ($x)
{
echo "is x";
}

Could just be

if ($x) echo "is x";

Ternary operator
My personal favorite, saves a lot of time and I still think it makes readable code

if ($type == 'human')
{
echo 'human';
} else {
echo 'robot';
}

Or why not..

echo ($type == 'human') ? 'human' : 'robot';

You can even set variables using that method

$type_of_person = ($type == 'human') ? 'human' : 'robot';

Verifying zero values not being false
Sometimes we deal with a function that can return a number and we want to make sure it returns a number, but if it returns 0, PHP will consider it as false.

if (getNumber()) { …. }

The number can return 0 and be as false, where as the following will not consider the integer 0 false

if (getNumber() !== false) { … }

Alternative control structure syntax
This is a great feature to do when you’re trying to do a lot of PHP work with HTML, it would be hard to list all of them but you can refer to it here: http://www.php.net/manual/en/control-structures.alternative-syntax.php.

Feel free to post any other ones in the comments section.. we all have that one trick we always use!

  • Andrew

    I think these are all extremely common shortcuts that are often used to even improve readability. I would be a little worried if a programmer didn't know at least 6/7 of these.

    • vexxhost

      Agreed :)

      They do fall under the basics but most people miss those ones

    • http://www.illustudios.com Omar Abdallah

      Indeed, Andrew

  • Chris

    Good post. I agree with every point except the braces. Leaving them out is very common source of errors when code gets added/modified or commented out.

    • http://twitter.com/terrianns @terrianns

      I tend to agree with you about the braces – ternary operators are handy but for handling if/else I always use braces or recently I use if():: endif; especially when I'm wrapping my if/else decision around a loop, switch or with more if/else's

  • http://www.codeblog.ch Remo

    Nice list, but be careful with short-hand print statements, short tags are often disabled and therefore don't work on all PHP hosts.

    • vexxhost

      You do have a point, also PHP lists that option PHP_INI_PERDIR so ini_set(..) can't help.

      I am not sure but I think you could get away with this

      <?php=$string?>

      I'll have to check that.

  • Ollie

    Sorry that hint about brackets and short tags, ie <?=$string?> inhibits readability of the code which makes maintaining the code base a major pain. Also you should always be using strict comparisons, ie === or !== in your code anyway for two reasons. It avoids coding errors by explicitly checking for data type comparisons and 2, it makes your code run faster because there is no type switching when the comparison is made.

    • vexxhost

      I agree, you do have a valid point regarding the === and !==

      However, for the short tags, I still think it's alright to do.. Especially in files where all that you're doing is displaying templates, CodeIgniter suggests that you use them in the views: http://codeigniter.com/user_guide/general/alterna

      • Philip

        No it's not. Don't ever use short print tags, it's really bad programming style, and most if not all of the major developers of the PHP language will agree with that. Leaving out braces results in logical errors when you add debug statements to your code because you invariably forget to add the braces at that time. 25 years of programming has taught me to always use block delimiters

    • http://script-dev.com ivanhoe

      i have to dissagre with you, PHP is not weak-typed language and I really think people should learn to enjoy that or to simply change the language they use, rather than trying to turn PHP into something it's not. IMHO, with your suggestion we have 2 situations, and I believe neither is better than simply using ==. We can have 2 different types, in which case we need to make the type casting manually first, before comparison. Not just that it's overhead, but it's very easy to forget to do the casting, and being weak-typed language, php will not warn us about that, which will break the logic in a really hard to find way. Also it's not faster either as you need to do the type casting manually, anyway. And then we have the other situation that both variables are of the same type, when it really doesn't matter how you write it, but again I think == is safer in the case of future changes that could break the code. Well just my $0.02

  • OIS

    Code readability, maintainability and coding standard are more important then saving a few keyboard punches. You listed most of what is often abused in code.

  • http://code.google.com/p/yapeal/ dragonrun1

    I've always thought the way most people write braces was wasteful so instead of
    if ($something !== $somethingelse)
    {
    print $something;
    }
    else
    {
    print $somethingelse;
    };
    I always use
    if ($something !== $somethingelse) {
    print $something;
    } else {
    print $somethingelse;
    };
    I've used that in my own project since the start and everyone that has ever commented have said the code was extremely easy to read and understand vs most other code they've seen. It also has the advantage of not wasting a bunch of space so more code is visible while still allowing adding more lines without causing errors. Most good editors have option to highlight the matching braces when coding so there is no need to have them on a line by themselves just so you can visually match them up yourself.

  • lfx

    $int++; or ++$int;
    $int–; or –$int;
    This way is faster.

  • http://twitter.com/deth_2_jt @deth_2_jt

    this are pretty common shortcuts and most should already be noted. Props to for combining them all in one neat area of information

  • Andy

    The one line if statement and the shorthand for echo are both bad practices. Do not do either of them. The if statement becomes less readable and requires more typing if you need to edit it later on. The shorthand php only works if it’s set up to work so your code could break on some servers

  • http://2web-master.ru 2web

    thanks a lot.
    useful article

  • João Pedro Costa

    If the point is cut out the unnecessary, what I think is somewhat problematic in the case of conditionals without braces, you can ommit the parentheses on using the ternary operator, also my favorite.

  • http://twitter.com/jakenoble @jakenoble

    Some interesting tips on using PHP comments more effectively here: http://forrst.com/posts/How_I_comment_my_PHP_code

    I love the Ternary Operator, although never ever nest them, it will kill your brain!

  • Meketrefe

    What a piece of crap! Instead of teaching good coding practices, this article does the opposite…

  • tirith

    HI,

    I m lakmey .PHP can do any thing that u cant't thiks

  • http://www.devarticles.in Arvind K.

    I don't think it's a good idea to have short tagsi.e. <?=$string?> while coding the big reason for that is its dependency on the ini setting for short open tag. Also i had read somewhere that it could be deprecated sometime in future??

  • http://forexhelptopics.info/ solY Mounir

    I don't think it's a good idea to have short tagsi.e. <?=$string?> while coding the big reason for that is its dependency on the ini setting for short open tag. Also i had read somewhere that it could be deprecated sometime in future??