5

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;
Community
  • 1
  • 1
Sliq
  • 15,937
  • 27
  • 110
  • 143

4 Answers4

4
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.

Rebirth
  • 1,011
  • 8
  • 14
  • 3
    Using `@` is officially very bad syntax as it surpresses notices (I think the PSR guys have defined that). Not an option in modern development anymore! – Sliq Aug 11 '14 at 23:16
  • 4
    I quote: "It's not exactly the right way to do it, but...". – Rebirth Aug 11 '14 at 23:17
  • 2
    My +1 is for your first example. Your second doesn't solve the "only write the variable once" part though. – scrowler Aug 11 '14 at 23:30
3

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())

scrowler
  • 24,273
  • 9
  • 60
  • 92
2

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>');
Christian Gollhardt
  • 16,510
  • 17
  • 74
  • 111
2

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.

Ende Neu
  • 15,581
  • 5
  • 57
  • 68