demosthenes.info

A blog by Dudley Storey on , , , , , , and anything else that strikes his fancy.

featured articles

popular favourites

shortcuts

Useful PHP Syntax Shortcuts

As a general rule, code is like writing: the more concise it is, the better. Fewer characters tend to mean lower errors, and fewer bugs. To this end, there are a few syntax shortcuts that are very useful.

if shortcut – no braces

If your if statement has only one directive, like the following:

  1. if ($x) { echo “This directive”; }

You can drop the braces:

  1. if ($x) echo “This directive”;

if-else shortcut

You’re probably used to the long, formal version of the if-else statement in PHP:

  1. if ($x == 5) { $y = 3 } else { $y = 2 }

While there is nothing wrong with this statement, it’s more efficient to use the shortened version, using the ternary operator:

  1. ($x == 5) ? $y = 3 : $y = 2;

echo shortcut

echo has a shortcut too, so long as the shortcut for the PHP tag itself is supported on the server. This is particularly useful if you are echoing out small snippets as variables. So rather than:

  1. You have chosen <?php echo $foo; ?> widgets.

You can use:

  1. You have chosen <?=$foo?> widgets.

Ah yes... Condensed if statements always seem to bite me in the ass whenever I use them. -__-

posted by Ian Carson

web developer guide

featured comment

by JoelB in Goodbye, JQuery Validation: HTML5 Form Errors With CSS3

what i'm reading

A Storm of Swords: A Song of Ice and Fire: Book Three
A Storm of Swords: A Song of Ice and Fire: Book Three

what i'm watching

Californication: The Third Season
Californication: The Third Season

what i'm playing

Mass Effect 3 Collector's Edition
Mass Effect 3 Collector's Edition

what i'm hearing

Dub FX
Dub FX

blogs

podcasts

no ads ever

This blog is free of advertising, and always will be.

creative commons licensed

The content of this blog is free to use in whatever way you wish under the Creative Commons license.