What is the PHP shorthand for: print var if var exist
Asked Answered
V

11

39

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.

Vestment answered 29/4, 2011 at 19:28 Comment(2)
echo (isset($var) ? $var : '') is about as short as you can get and be syntactically correct.Soapbark
without making a function for it I think @Marc B has provided the shortest way to do it... in a comment no less!Radiolocation
H
90

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');
Henpeck answered 29/4, 2011 at 19:43 Comment(8)
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.Radiolocation
@afuzzyllama: Because I need to pass a potentially undefined variable. If I left out the reference it would give you a Undefined Variable Notice ;)Henpeck
@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.)Henpeck
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.Emptyhanded
Not a big fan of this. PHP should throw an undefined variable warning when you pass it by reference as well.Sidestep
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.Finger
the best definition for "shorhand" is in this answer with the ?? operator which I didn't knew until now :)Trixy
Please can you tell me why you put & before $var like &$var?Intersex
I
11

Another option:

<input value="<?php echo isset($var) ? $var : '' ?>">
Irritability answered 29/4, 2011 at 19:35 Comment(2)
Yes, but it will also issue a E_NOTICE. Checking if it is set first fixes this.Irritability
+1 and <input value="<?=isset($var) ? $var : '' ?>"> makes this even shorter.Cayuse
T
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!

Toaster answered 31/8, 2015 at 9:15 Comment(1)
and is just an alias of the logical operator &&, but nobody uses it. Your code is the same as isset($var) && print($var);Olnton
D
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];
}
Dawndawna answered 29/4, 2011 at 19:30 Comment(2)
Sorry, looking for a solution for non-global vars.Vestment
In this case.. get a template engine.Dawndawna
T
0
<input value='<?php @print($var); ?>'>
Tapeworm answered 29/4, 2011 at 19:31 Comment(3)
Error/warning/notice suppression is pretty dirty.Dawndawna
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.Tapeworm
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.Angio
P
0

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

Pinsk answered 29/4, 2011 at 19:31 Comment(11)
Error/warning/notice suppression is pretty dirty.Dawndawna
@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 allowableSoapbark
@Marc B: Except if you're going to do that, then why not just turn off warnings?Marlborough
@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.Soapbark
I agree 100%, but it's a legitimate answer to the question.Pinsk
Using @ the code will still produce a warning but will just silence it, which tends to slow things down a bit.Backhouse
@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 :)Lorelle
@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.Soapbark
@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).Summation
@mario: I'm not talking about optimization - I'm talking about best practices :)Lorelle
@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.Lorelle
B
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.

Backhouse answered 29/4, 2011 at 19:36 Comment(1)
Shouldn't that be if (isset($variable)) {Kkt
B
0

This worked for me:

<?= isset($my_variable) ? $my_variable : $my_variable="Some Value"; ?>
Blanton answered 29/3, 2016 at 18:50 Comment(0)
M
-1
<input value='<?php printvar(&$myvar); ?>' />

function printvar(&$val) {
    if (isset($val)) echo $val;
}
Marlborough answered 29/4, 2011 at 19:32 Comment(2)
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.Dawndawna
@ThiefMaster: Thought the same thing at the same time :-)Marlborough
D
-1

You could also use the following:

<input type="text" value="<?php echo @$var; ?>">//means if(isset($var)){ echo $var; }
Directorate answered 12/1, 2019 at 13:9 Comment(1)
This answer has been given earlier, please abstain from posting double answers as it only adds distraction.Goodish
R
-4
$var;
(isset($var)) ? (print $var) : '';

$var = 'hello var';
(isset($var)) ? (print $var) : '';
Rau answered 29/4, 2011 at 19:31 Comment(2)
Pretty complex... I mean a lot of opportunity to write syntax errors.Vestment
I especially find the parentheses around the isset() and the print very adorable.Horseman

© 2022 - 2024 — McMap. All rights reserved.