PHP - 如果变量不为空,则回显一些 html 代码

2022-08-30 10:49:57

如果变量不为空,我想显示一些html代码,否则我不想显示任何内容。

我尝试过这个代码,但不起作用:

<?php 
    $web = the_field('website');
    if (isset($web)) {
?>
       <span class="field-label">Website: </span><a href="http://<?php the_field('website'); ?>" target="_blank"><?php the_field('website'); ?></a> 
<?php
    } else { 
        echo "Niente";
    }
?>

答案 1
if (!empty($web)) {
?>
    <span class="field-label">Website:  </span><a href="http://<?php the_field('website'); ?>" target="_blank"><?php the_field('website'); ?></a> 
<?php
} else { echo "Niente";}

http://us.php.net/manual/en/function.empty.php


答案 2

isset即使变量为 “”,也将返回 true。 仅当变量为 null 时才返回 false。你应该做什么:isset

if (!empty($web)) {
    // foo
}

这将检查变量是否为空。

希望这有帮助


推荐