What is the PHP shorthand for: print var if var exist
Solution 1
For PHP >= 5.x:
My recommendation would be to create a issetor
function:
function issetor(&$var, $default = false) {
return isset($var) ? $var : $default;
}
This takes a variable as argument and returns it, if it exists, or a default value, if it doesn't. Now you can do:
echo issetor($myVar);
But also use it in other cases:
$user = issetor($_GET['user'], 'guest');
For PHP >= 7.0:
As of PHP 7 you can use the null-coalesce operator:
$user = $_GET['user'] ?? 'guest';
Or in your usage:
<?= $myVar ?? '' ?>
Solution 2
Another option:
<input value="<?php echo isset($var) ? $var : '' ?>">
Solution 3
The shortest answer I can come up with is <?php isset($var) AND print($var); ?>
Further details are here on php manual.
'; // This is an alternative isset( $value ) AND print( $value ); ?>A simple alternative to an if statement, which is almost like a ternary operator, is the use of AND. Consider the following:
This does not work with echo() for some reason. I find this extremely useful!
Solution 4
<input value='<?php @print($var); ?>'>
bart
Updated on January 23, 2020Comments
-
bart over 4 years
We've all encountered it before, needing to print a variable in an input field but not knowing for sure whether the var is set, like this. Basically this is to avoid an e_warning.
<input value='<?php if(isset($var)){print($var);}; ?>'>
How can I write this shorter? I'm okay introducing a new function like this:
<input value='<?php printvar('myvar'); ?>'>
But I don't succeed in writing the printvar() function.
-
ThiefMaster about 13 yearsError/warning/notice suppression is pretty dirty.
-
ThiefMaster about 13 yearsError/warning/notice suppression is pretty dirty.
-
bart about 13 yearsPretty complex... I mean a lot of opportunity to write syntax errors.
-
bart about 13 yearsSorry, looking for a solution for non-global vars.
-
ThiefMaster about 13 yearsWon't work. Passing the var to the function will cause the notice. Not sure if it would work with a reference... might be worth a try.
-
mellamokb about 13 years@ThiefMaster: Thought the same thing at the same time :-)
-
ThiefMaster about 13 yearsIn this case.. get a template engine.
-
Marc B about 13 years@demian / thief: I'd agree if it was to supress a function's error, but frankly, supressing the "not defined" warning on a variable in an output situation is allowable
-
mellamokb about 13 years@Marc B: Except if you're going to do that, then why not just turn off warnings?
-
Marc B about 13 years@mella: in some cases you don't have that level of control of the server, which is where the usual "ZOMG DON'T EVER USE SHORTTTAGS! THEY ARE TEH BAD!!!!!" breathelessly panicky warnings come from.
-
Dan Breen about 13 yearsI agree 100%, but it's a legitimate answer to the question.
-
mfonda about 13 yearsUsing
@
the code will still produce a warning but will just silence it, which tends to slow things down a bit. -
Demian Brecht about 13 years@Marc B: Logically I agree, however, if someone more junior than you reads the code and says "ohh it's okay to use suppression", I guarantee you'll find it littered throughout the rest of the code that they write :) I think the overhead of writing in an
isset
orempty
is much more preferable than bad habits :) -
Marc B about 13 years@demian: that's like saying we shouldn't have knives in the kitchen for dinner prep because they can be used to stab people in back alleys. Appropriate tools for appropriate jobs, and in the cases where you can't disable the warnings, suppression is the best bet, unless you want gunk up your code with repeated
echo (isset($var) ? $var : '')
constructs. -
mario about 13 years@Demian: Let me clear up that meme by citing from the default error handler in the PHP source code:
case E_NOTICE: /* notices are no errors and are not treated as such like E_WARNINGS */
-- And the syntactic isset littering accomplishes little (micro optimization) over using the intended language construct for handling debug messages (=notices). -
Demian Brecht about 13 years@mario: I'm not talking about optimization - I'm talking about best practices :)
-
Demian Brecht about 13 years@Mark B: If you're following current PHP OO practices, there's no reason that you can't have a static helper function with containing the otherwise redundant code.
-
Galen about 13 yearsYes, but it will also issue a E_NOTICE. Checking if it is set first fixes this.
-
afuzzyllama about 13 yearsWhy are you doing a call by reference? Isn't value enough? Also, default is a keyword in PHP, it might be wise to not use that as a function name. It had weird results on my server.
-
NikiC about 13 years@afuzzyllama: Because I need to pass a potentially undefined variable. If I left out the reference it would give you a Undefined Variable Notice ;)
-
NikiC about 13 years@afuzzyllama: Thanks for pointing out, renamed it to
issetor
(I think that's how they named it, when they wanted to implement it in PHP 6, but I'm not quite sure.) -
arychj about 13 yearsIt's dirty if it's suppressing an actual error. Is it really worth it to spend the time, or increase the complexity of the code when a simpler solution will suffice? As long as you are aware of what you are doing, and why the warning is being suppressed this is fine.
-
Red Taz over 12 yearsShouldn't that be
if (isset($variable)) {
-
Sam Dufel about 11 yearsOne thing about this method - calling
issetor
asissetor($var['key'])
will injectkey
into$var
. In some cases, you might end up with unexpected behavior, particularly if you're iterating over keys later. -
Dmytro Dzyubak almost 10 years+1 and
<input value="<?=isset($var) ? $var : '' ?>">
makes this even shorter. -
Mahn over 9 yearsNot a big fan of this. PHP should throw an undefined variable warning when you pass it by reference as well.
-
Imperative over 9 yearsIn a lot of cases, I'd swap that for an !empty() instead. It's a very clever little line of code though, especially when combined with a sprintf() on the output.
-
pfrenssen over 8 yearsI especially find the parentheses around the
isset()
and theprint
very adorable. -
RicardoE over 7 yearsthe best definition for "shorhand" is in this answer with the ?? operator which I didn't knew until now :)
-
unity100 about 7 yearsThere can be no errors in printing or echoing a variable. If the variable doesnt exist, it wont print. If there is something to print, php will take care for it. arychj is right.
-
duhok over 5 yearsPlease can you tell me why you put & before $var like &$var?
-
Paul over 5 yearsThis answer has been given earlier, please abstain from posting double answers as it only adds distraction.
-
BadHorsie almost 4 years
and
is just an alias of the logical operator&&
, but nobody uses it. Your code is the same asisset($var) && print($var);