Check if a variable is empty

前端 未结 4 1556
南旧
南旧 2020-12-11 13:10

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

Term:
相关标签:
4条回答
  • 2020-12-11 13:42

    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.

    0 讨论(0)
  • 2020-12-11 13:43
    <?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

    0 讨论(0)
  • 2020-12-11 13:46
    <?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
        }
    ?>
    
    0 讨论(0)
  • 2020-12-11 13:53

    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 讨论(0)
提交回复
热议问题