Sliq
Sliq

Reputation: 16504

Can 'if X, then echo X' be shortened in 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;

Upvotes: 5

Views: 304

Answers (4)

Rebirth
Rebirth

Reputation: 1011

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.

Upvotes: 4

Christian Gollhardt
Christian Gollhardt

Reputation: 17034

Yes, you can write a function:

function echoIfNotEmpty($val) {
   if (!empty($val)) {
       echo $val;
   }
}

Usage:

echoIfNotEmpty($x);

Sure you can shorten the function name.


If you don't know, if the var is intialized you can also do:

function echoIfNotEmpty(&$val = null) {
   if (!empty($val)) {
       echo $val;
   }
}

Most times we want do prefix and append something

function echoIfNotEmpty(&$val = null, $prefix = '', $suffix = '') {
   if (!empty($val)) {
       echo $prefix . $val . $suffix;
   }
}

echoIfNotEmpty($x, '<strong>', '</strong>');

Upvotes: 2

scrowler
scrowler

Reputation: 24435

Built in? No.

However - you could write your own wrapper function to do it:

$x = 'foobar';
myecho($x); // foobar

function myecho($x) {
    echo !empty($x) ? $x : '';
}

This fits the bill of "only writing the variable once", but doesn't give you as much flexibility as the echo command does because this is a function that is using echo, so you can't do something like: myecho($x . ', '. $y) (the argument is now always defined and not empty once it hits myecho())

Upvotes: 3

Ende Neu
Ende Neu

Reputation: 15783

Easy approach would be to define an helper function so:

function mEcho($someVariable) {
  if(!empty($someVariable) echo $someVariable;
}

I'm not sure though if that's what you intended.

Upvotes: 2

Related Questions