38

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.

bart
  • 14,958
  • 21
  • 75
  • 105
  • 7
    `echo (isset($var) ? $var : '')` is about as short as you can get and be syntactically correct. – Marc B Apr 29 '11 at 19:43
  • without making a function for it I think @Marc B has provided the shortest way to do it... in a comment no less! – afuzzyllama Apr 29 '11 at 21:56

11 Answers11

87

For PHP >= 7.0:

As of PHP 7 you can use the null-coalesce operator:

$user = $_GET['user'] ?? 'guest';

Or in your usage:

<?= $myVar ?? '' ?>

For PHP >= 5.x:

My recommendation would be to create a issetor function:

function issetor(&$var, $default = null) {
    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');
NikiC
  • 100,734
  • 37
  • 191
  • 225
  • 2
    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. – afuzzyllama Apr 29 '11 at 22:15
  • 15
    @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 Apr 29 '11 at 22:18
  • @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.) – NikiC Apr 29 '11 at 22:23
  • 3
    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. – Sam Dufel Apr 09 '13 at 21:59
  • Not a big fan of this. PHP should throw an undefined variable warning when you pass it by reference as well. – Mahn Jan 24 '15 at 16:22
  • 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. – Imperative Feb 06 '15 at 00:40
  • the best definition for "shorhand" is in this answer with the ?? operator which I didn't knew until now :) – RicardoE Jan 19 '17 at 18:19
  • Please can you tell me why you put & before $var like &$var? – duhok Nov 13 '18 at 12:31
11

Another option:

<input value="<?php echo isset($var) ? $var : '' ?>">
Galen
  • 29,976
  • 9
  • 71
  • 89
2

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!

McAngujo
  • 115
  • 2
  • 8
  • `and` is just an alias of the logical operator `&&`, but nobody uses it. Your code is the same as `isset($var) && print($var);` – BadHorsie Sep 20 '20 at 20:46
0

This worked for me:

<?= isset($my_variable) ? $my_variable : $my_variable="Some Value"; ?>
Jani
  • 349
  • 3
  • 8
0

Better use a proper template engine - https://stackoverflow.com/q/3694801/298479 mentions two nice ones.

Here's your function anyway - it will only work if the var exists in the global scope:

function printvar($name) {
    if(isset($GLOBALS[$name])) echo $GLOBALS[$name];
}
Community
  • 1
  • 1
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
0
<input value='<?php @print($var); ?>'>
arychj
  • 711
  • 3
  • 21
  • 19
    Error/warning/notice suppression is pretty dirty. – ThiefMaster Apr 29 '11 at 19:32
  • 3
    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. – arychj May 27 '11 at 19:58
  • 1
    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. – unity100 Jun 30 '17 at 21:39
0

You could do <?php echo @$var; ?>. Or <?= @$var ?>.

Dan Breen
  • 12,626
  • 4
  • 38
  • 49
  • 18
    Error/warning/notice suppression is pretty dirty. – ThiefMaster Apr 29 '11 at 19:32
  • 3
    @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 – Marc B Apr 29 '11 at 19:34
  • @Marc B: Except if you're going to do that, then why not just turn off warnings? – mellamokb Apr 29 '11 at 19:35
  • 1
    @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. – Marc B Apr 29 '11 at 19:36
  • I agree 100%, but it's a legitimate answer to the question. – Dan Breen Apr 29 '11 at 19:36
  • Using `@` the code will still produce a warning but will just silence it, which tends to slow things down a bit. – mfonda Apr 29 '11 at 19:38
  • 1
    @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 :) – Demian Brecht Apr 29 '11 at 19:39
  • 5
    @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. – Marc B Apr 29 '11 at 19:43
  • @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). – mario Apr 29 '11 at 19:47
  • @mario: I'm not talking about optimization - I'm talking about best practices :) – Demian Brecht Apr 29 '11 at 19:51
  • @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. – Demian Brecht Apr 29 '11 at 19:52
0

There's currently nothing in PHP that can do this, and you can't really write a function in PHP to do it either. You could do the following to achieve your goal, but it also has the side effect of defining the variable if it doesn't exist:

function printvar(&$variable)
{
    if (isset($variable)) {
        echo $variable;
    }
}

This will allow you to do printvar($foo) or printvar($array['foo']['bar']). However, the best way to do it IMO is to use isset every time. I know it's annoying but there's not any good ways around it. Using @ isn't recommended.

For more information, see https://wiki.php.net/rfc/ifsetor.

mfonda
  • 7,873
  • 1
  • 26
  • 30
-1

You could also use the following:

<input type="text" value="<?php echo @$var; ?>">//means if(isset($var)){ echo $var; }
Employee
  • 3,109
  • 5
  • 31
  • 50
  • This answer has been given earlier, please abstain from posting double answers as it only adds distraction. – Paul Jan 28 '19 at 14:45
-1
<input value='<?php printvar(&$myvar); ?>' />

function printvar(&$val) {
    if (isset($val)) echo $val;
}
mellamokb
  • 56,094
  • 12
  • 110
  • 136
-4
$var;
(isset($var)) ? (print $var) : '';

$var = 'hello var';
(isset($var)) ? (print $var) : '';
Phill Pafford
  • 83,471
  • 91
  • 263
  • 383