开发者

Check if a variable is empty

开发者 https://www.devze.com 2022-12-27 01:11 出处:网络
I have some user-submitted variables that I want to display in a different part of my site like this:

I have some user-submitted variables that I want to display in a different part of my site like this:

<div class="pre_box">Term: </div>
<div class="entry"><?php $key='term'; echo get_post_meta($post->ID, $key, true); ?></div>

Occasionally, these variables might be empty in which case I don't want to display the label for the empty variable. In the example above I would want to hide the <div class="pre_box">Term: 开发者_StackOverflow社区</div> part. Is there some simple way to check if a php variable like the one above is empty and prevent the label from being displayed?

Update, here is the code using !empty

<?php $key='term' ?>
<?php if( !empty( $key ) ): ?> 
<div class="pre_box">Term: </div>
<div class="entry">
<?php echo get_post_meta($post->ID, $key, true); ?>
</div> 
<?php endif; ?>

However, this still displays the content no matter what. I think the problem might be in the way I am defining the $key variable. Im trying to pull data from a custom field set in a wordpress post - thats what the $post->ID business is all about.


<?php 
    $post_meta = get_post_meta($post->ID, 'term', true);
    if (!empty($post_meta)) {
?>
        <div class="pre_box">Term: </div>
        <div class="entry"><?php echo $post_meta; ?></div>
<?php
    }
?>


If isset() does not work, try empty() instead:

<?php if( !empty( $key ) ): ?> 
    <div class="pre_box">Term: </div>
    <div class="entry">
         <?php echo get_post_meta($post->ID, $key, true); ?>
    </div> 
<?php endif; ?>

isset() will deliver TRUE if the value is set and has a value different from NULL.

empty() instead will deliver TRUE (hence !empty() results in FALSE) for:

  • "" (an empty string)
  • 0 (0 as an integer)
  • "0" (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • var $var; (a variable declared, but without a value in a class)

I assume your $key is set but with an empty string. Thus, empty() is the way to go here.


<?php if( isset( $var ) ): ?><p><?php echo $var ?></p><?php endif; ?>

If $var is set it will display the paragraph with $var, otherwise nothing will be displayed


Well they way your code is above, $key will never be empty, thus the pre_box will always be displayed. You're setting $key = 'term', which gives it a value so !empty($key) or isset($key) will always be true.

Casey's solution should give you the result you're going for.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号