如果PHP变量为空,如何隐藏几行内容?

3

作为一个PHP学习者,如果选择的变量为空,我想隐藏多行显示内容。我可以在基本层面上实现这个功能,但是当需要隐藏的内容变得更加复杂时,我就有些迷茫了。我希望达到的效果是这样的:

<?php if (isset($g1)) { ?>
((This part should not display if variable $g1 is empty))
<?php } ?>

我的代码看起来像这样:

<?php if (isset($g1)) { ?>
<a href="img/g1.png"  class="lightbox"  rel="tooltip" data-original-title="<?php print $g1; ?>" data-plugin-options='{"type":"image"}'>
<img class="img-responsive img-rounded wbdr4" src="img/g1.png">
</a>
<?php } ?>

在上述代码中,当变量g1为空时,工具提示不会显示,但其他内容会显示。我是新来的,希望我的问题格式正确。感谢您的帮助。

看起来他们在使用那个......但是他们的编码风格在我的眼里非常难以阅读。 - Andrew
如果 ($g1 != NULL) { //img 标签 } - TBI
我建议您先看一下我的答案,因为这里的每个答案都误解了您的问题。(或者我是个傻瓜,其他人都是对的 :P) - Jacky Cheng
你可以使用 empty() 函数,它会处理所有情况。http://php.net/manual/zh/function.empty.php - Sougata Bose
只是想说我非常感谢所给予的帮助。这是一个很不错的社区! :-) - MGB
6个回答

2
<?php if (isset($g1) && $g1!='') { ?>
<a href="img/g1.png"  class="lightbox"  rel="tooltip" data-original-title="<?php print $g1; ?>" data-plugin-options='{"type":"image"}'>
<img class="img-responsive img-rounded wbdr4" src="img/g1.png">
</a>
<?php } ?>

2
Try this code:
<?php if (!empty($g1)) { ?>
((This part should not display if variable $g1 is empty))
<?php } ?>

0
你可以使用empty()函数:
<?php if (isset($g1) && !empty($g1)) { ?>
((This part should not display if variable $g1 is empty))
<?php } ?>

或者

<?php if (isset($g1) && $g1 !== '') { ?>
((This part should not display if variable $g1 is empty))
<?php } ?>

1
如果它不为空,那么肯定必须被设置。 - user557846
isset只检查null值,您仍然可以使用empty()检查空字符串。 - meda
isset()类似,empty()在使用未声明的变量时不会发出警告,并且应该返回FALSE - Havenard

0

isset() 函数检查变量是否已设置,即使为空字符串也是如此。还有一个 empty() 函数,它检查变量是否未设置或设置为空字符串。

<?php
$x = '';
if (isset($x)) print('$x is set');
if (empty($x)) print('$x is not set or is empty');
if (isset($x) && empty($x)) print('$x is set and is empty');
if (!empty($x)) print('$x is set and not empty'); // won't emit warning if not set

0
这是我的答案,似乎与其他人完全不同,我不知道为什么。
要做到OP想要的,一种方法是扩展php标记以包括所有内容。
<?php 
    if (isset($g1)) { 
        echo "<a href='img/g1.png'  class='lightbox'  rel='tooltip' data-original-title='".$g1."' data-plugin-options='{\"type\":\"image\"}'>";
        echo "<img class='img-responsive img-rounded wbdr4' src='img/g1.png'>";
        echo "</a>";
    } 
?>

-2

在 PHP 中隐藏某些内容非常容易,您可以使用多种方法,以下是它的实现方式:

<?php if(isset($g1) == ""): ?>
   //The $g1 is empty so anything here will be displayed
<?php else: ?>
   //The $g1 is NOT empty and anything here will be displayed
<?php endif; ?>

1
isset($g1) == ""... 真的吗? - Sam Dufel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接