Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
285 views
in Technique[技术] by (71.8m points)

php - Check if a variable is empty

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: </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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
<?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
    }
?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...