Maybe if X, then echo X 'will shrink in PHP?

The shortest way to drop material in views in PHP - if you do not use template engines - is, afaik, this one:

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

For a deeper explanation of why using !empty is a good choice, take a look here .

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

 !echo $x; 

or

 echo? $x; 
+5
source share
4 answers

Built? Not.

However - you can write your own wrapper function to do this:

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

This corresponds to the account β€œonly writing the variable once”, but does not give you such flexibility as the echo command, because it is a function that uses the echo, so you cannot do something like: myecho($x . ', '. $y) (the argument is now always defined and not empty when it falls into myecho() )

+3
source
 echo @$x; 

This is not quite the right way to do this, but it is shorter. this reduces the need to check if $ x exists, since @ ignores the error that occurs when $ x == null;

change

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

is a shorter way that is actually not much shorter and does not solve your problem.

Guess other answers offer the best solution by contacting to make a short function for it.

+4
source

Yes, you can write a function:

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

Using:

 echoIfNotEmpty($x); 

Of course, you can shorten the name of the function.


If you do not know if var is intialized you can also do:

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

In most cases, we want to prefix and add something

 function echoIfNotEmpty(&$val = null, $prefix = '', $suffix = '') { if (!empty($val)) { echo $prefix . $val . $suffix; } } echoIfNotEmpty($x, '<strong>', '</strong>'); 
+2
source

An easy approach would be to define an auxiliary function, therefore:

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

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

+2
source

Source: https://habr.com/ru/post/1200065/


All Articles