if()判断变量是不是为空的两种方法,哪种更好?有区别吗

WBOY
Libérer: 2016-06-13 12:53:48
original
1532 Les gens l'ont consulté

if()判断变量是否为空的两种方法,哪种更好?有区别吗?
学习研究wordpress时,有以下两种判断自定义域是否为空的方法,都用到了IF()。初学php,不知这两种方法有何区别,哪种效率更高一些?
// show the first value of the specified key inside a loop
$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

ID, 'url', true);

if($image) : ?>

 if()判断变量是不是为空的两种方法,哪种更好?有区别吗 " alt="" />


------解决方案--------------------
引用:
谢谢。按照if($image)的方法, if(key_1_value)不是更简洁吗?if($image)这种只把变量作参数的方法,可取吗?


if($image)和if(!$image)是完全相反的概念
举例来说
<br />
	$find=1;<br />
	if($find){<br />
		echo "find不为空";<br />
	}else{<br />
		echo "find为空";<br />
	}<br />
	//相当于<br />
	if(!$find){<br />
		echo "find为空";<br />
	}else{	<br />
		echo "find不为空";<br />
	}<br />
Copier après la connexion

也就是$find和!$find中if与else中的内容正好相反



------解决方案--------------------
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;
 } 
 //上面两个方法功能有点差别的,看你需求了
?>
Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!