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

吃可爱长大的小学妹 提交于 2019-11-27 04:22:06
NikiC

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 ?? '' ?>

Another option:

<input value="<?php echo isset($var) ? $var : '' ?>">
<input value='<?php @print($var); ?>'>

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!

ThiefMaster

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];
}

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

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.

This worked for me:

<?= isset($my_variable) ? $my_variable : $my_variable="Some Value"; ?>
<input value='<?php printvar(&$myvar); ?>' />

function printvar(&$val) {
    if (isset($val)) echo $val;
}
Waseem Akhter

You could also use the following:

<input type="text" value="<?php echo @$var; ?>">//means if(isset($var)){ echo $var; }
$var;
(isset($var)) ? (print $var) : '';

$var = 'hello var';
(isset($var)) ? (print $var) : '';
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!