如果php变量为空,如何隐藏几行?
作为一名PHP学习者,如果所选变量为空,我很难隐藏显示几行代码。我可以让它在一个基本的层面上工作,但当要隐藏的内容变得更加复杂时,我就不知所措了。我的目标是:如果php变量为空,如何隐藏几行?,php,variables,show-hide,is-empty,Php,Variables,Show Hide,Is Empty,作为一名PHP学习者,如果所选变量为空,我很难隐藏显示几行代码。我可以让它在一个基本的层面上工作,但当要隐藏的内容变得更加复杂时,我就不知所措了。我的目标是: <?php if (isset($g1)) { ?> ((This part should not display if variable $g1 is empty)) <?php } ?> ((如果变量$g1为空,则不应显示此部分)) 我的代码如下所示: <?php if (isset($g1)) {
<?php if (isset($g1)) { ?>
((This part should not display if variable $g1 is empty))
<?php } ?>
((如果变量$g1为空,则不应显示此部分))
我的代码如下所示:
<?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为空时,工具提示不会显示,但其余的会显示。我是新来的,所以,我希望我的问题格式正确。感谢您的帮助。如果
empty()
函数:
<?php if (isset($g1) && !empty($g1)) { ?>
((This part should not display if variable $g1 is empty))
<?php } ?>
((如果变量$g1为空,则不应显示此部分))
或
((如果变量$g1为空,则不应显示此部分))
在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; ?>
//$g1为空,因此此处的任何内容都将显示
//$g1不是空的,将显示此处的任何内容
函数检查变量是否已设置,即使设置为空字符串也是如此。有一个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
尝试以下代码:
((如果变量$g1为空,则不应显示此部分))
这是我的答案,它似乎走了一条与其他人完全不同的道路,我不知道为什么
要做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>";
}
?>
看起来他们正在使用它。。但是他们的编码风格在我看来是很难理解的。使用if($g1!=NULL){//img tag}我建议先看看我的答案,因为这里的每个答案都误解了你的问题。(或者我是idoit,其他人都是对的:P)你可以使用empty()函数,它会处理所有的问题。我只想说一句话,感谢你的帮助。这是一个了不起的社区!:-)<代码>设置($g1)=“”
。。。真的吗?如果它不是空的,那么它一定是setisset。只要检查null,您仍然可以使用empty()检查空字符串,而无需这样做。就像isset()
,empty()
与未声明的变量一起使用时不会发出警告,如果未声明,则应返回FALSE
。
<?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
Try this code:
<?php if (!empty($g1)) { ?>
((This part should not display if variable $g1 is empty))
<?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>";
}
?>