Minimal PHP—less, but better

Post #7, veröffentlicht am in
  • Web design

As always (😬), I am most likely late to the party, but have you enjoyed writing shorthand PHP, yet?

Shorter if statements

For me, it all started when I realize, that this block of code

if(condition) {
  echo ’some text’;
} else {
  echo ’some other text’;

can be turned into this:

echo (condition) ? ’some text’ : ’some other text’;

Neat, ey?
Likewise this can be used to define variables.

This syntax has its limits, of course. You wouldn’t want to write more complex statements like that. It is more of a one-liner thing.

(Am I boring you with my unspectacular findings already? Well,…if you’ve come this far, you might as well keep at it. 😉)

The <?= short tag

Only a few weeks ago I came across this little gem in the Kirby CMS docs:

<?= ’some text’ ?>

The <?= is a shorthand for “echo this piece of PHP”.

Bringing together, what belongs together

Taking the last code block a step further, you might end up with this:

<?= (condition) ? ’some text’ : ’some other text’ ?>

So cool!
This is particular handy, if you want to echo some small piece of conditional content inline in your HTML. E.g. when prefilling a form.

Once you get the hang of it, your code will even be much more readable.

Hope, you share my enthusiasm. 😊

I bet, there is tons more.
Send me your favorite minimal PHP snippet on Mastodon!