学习研究wordpress时,有以下两种判断自定义域是否为空的方法,都用到了IF()。初学php,不知这两种方法有何区别,哪种效率更高一些?
// show the first value of the specified key inside a loop
<?php
$key_1_value = get_post_meta($post->ID, 'key_1', true);
// check if the custom field has a value
if($key_1_value != '') {
echo $key_1_value;
}
?>// display an image based on custom-field value, if it exists<?php $image = get_post_meta($post->ID, 'url', true);
if($image) : ?> <img src="<?php echo $image; ?>" alt="" /> <?php endif; ?>
// show the first value of the specified key inside a loop
<?php
$key_1_value = get_post_meta($post->ID, 'key_1', true);
// check if the custom field has a value
if($key_1_value != '') {
echo $key_1_value;
}
?>// display an image based on custom-field value, if it exists<?php $image = get_post_meta($post->ID, 'url', true);
if($image) : ?> <img src="<?php echo $image; ?>" alt="" /> <?php endif; ?>
$key_1_value != ''(1)
替换成
if(!$key_1_value)(2)
和
if(!empty($key_1_value))(3)比较一下
我个人习惯(2),效率方面如果差不多的话,至少这样写比较简洁
if($image)和if(!$image)是完全相反的概念
举例来说 $find=1;
if($find){
echo "find不为空";
}else{
echo "find为空";
}
//相当于
if(!$find){
echo "find为空";
}else{
echo "find不为空";
}也就是$find和!$find中if与else中的内容正好相反
if($x!='')
和
if($x)
不是完全一样的......试试$x="0";
if($key_1_value!='') {//这里是指$key_1_value只要不为空就可以,$key_1_value=0也是不为空 所有$key_1_value=0也是可以通过的
echo $key_1_value;
}
if($key_1_value) {//这里是指$key_1_value为真,所谓真就是$key_1_value不能为空也不能为0,这个条件比上面多出一个$key_1_value不能为0
echo $key_1_value;
}
//上面两个方法功能有点差别的,看你需求了
?>