Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can 'if X, then echo X' be shortened in PHP?

Tags:

php

The shortest way to echo out stuff in views in PHP - when not using template engines - is, afaik, this one:

<?php if (!empty($x)) echo $x; ?>

For a deeper explanaition why using !empty is a good choice please look here.

Is it possible to write this without writing the variable name twice (like in other languages), something like

!echo $x;

or

echo? $x;
like image 517
Sliq Avatar asked Aug 11 '14 23:08

Sliq


1 Answers

echo @$x;

It's not exactly the right way to do it, but it is shorter. it reduces the need to check if $x exists since @ silences the error thrown when $x == null;

edit

echo empty($x) ? "" : $x;

is a shorter way, which is not really that much shorter nor does it solve your problem.

guess the other answers offer a better solution by addressing to make a short function for it.

like image 127
Rebirth Avatar answered Sep 22 '22 19:09

Rebirth