What is the PHP shorthand for: print var if var exist

31,982

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.

A simple alternative to an if statement, which is almost like a ternary operator, is the use of AND. Consider the following:

'; // This is an alternative isset( $value ) AND print( $value ); ?>

This does not work with echo() for some reason. I find this extremely useful!

Solution 4

<input value='<?php @print($var); ?>'>
Share:
31,982
bart
Author by

bart

Updated on January 23, 2020

Comments

  • bart
    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
    ThiefMaster about 13 years
    Error/warning/notice suppression is pretty dirty.
  • ThiefMaster
    ThiefMaster about 13 years
    Error/warning/notice suppression is pretty dirty.
  • bart
    bart about 13 years
    Pretty complex... I mean a lot of opportunity to write syntax errors.
  • bart
    bart about 13 years
    Sorry, looking for a solution for non-global vars.
  • ThiefMaster
    ThiefMaster about 13 years
    Won'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
    mellamokb about 13 years
    @ThiefMaster: Thought the same thing at the same time :-)
  • ThiefMaster
    ThiefMaster about 13 years
    In this case.. get a template engine.
  • Marc B
    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
    mellamokb about 13 years
    @Marc B: Except if you're going to do that, then why not just turn off warnings?
  • Marc B
    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
    Dan Breen about 13 years
    I agree 100%, but it's a legitimate answer to the question.
  • mfonda
    mfonda about 13 years
    Using @ the code will still produce a warning but will just silence it, which tends to slow things down a bit.
  • Demian Brecht
    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 or empty is much more preferable than bad habits :)
  • Marc B
    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
    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
    Demian Brecht about 13 years
    @mario: I'm not talking about optimization - I'm talking about best practices :)
  • Demian Brecht
    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
    Galen about 13 years
    Yes, but it will also issue a E_NOTICE. Checking if it is set first fixes this.
  • afuzzyllama
    afuzzyllama about 13 years
    Why 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
    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
    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
    arychj about 13 years
    It'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
    Red Taz over 12 years
    Shouldn't that be if (isset($variable)) {
  • Sam Dufel
    Sam Dufel about 11 years
    One thing about this method - calling issetor as issetor($var['key']) will inject key into $var. In some cases, you might end up with unexpected behavior, particularly if you're iterating over keys later.
  • Dmytro Dzyubak
    Dmytro Dzyubak almost 10 years
    +1 and <input value="<?=isset($var) ? $var : '' ?>"> makes this even shorter.
  • Mahn
    Mahn over 9 years
    Not a big fan of this. PHP should throw an undefined variable warning when you pass it by reference as well.
  • Imperative
    Imperative over 9 years
    In 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
    pfrenssen over 8 years
    I especially find the parentheses around the isset() and the print very adorable.
  • RicardoE
    RicardoE over 7 years
    the best definition for "shorhand" is in this answer with the ?? operator which I didn't knew until now :)
  • unity100
    unity100 about 7 years
    There 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
    duhok over 5 years
    Please can you tell me why you put & before $var like &$var?
  • Paul
    Paul over 5 years
    This answer has been given earlier, please abstain from posting double answers as it only adds distraction.
  • BadHorsie
    BadHorsie almost 4 years
    and is just an alias of the logical operator &&, but nobody uses it. Your code is the same as isset($var) && print($var);