isset()和empty()-使用什么 [英] isset() and empty() - what to use

查看:92
本文介绍了isset()和empty()-使用什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您能帮我改善编码风格吗?:)在某些任务中,我需要检查-变量是否为空或包含某些内容.为了解决此任务,我通常执行以下操作.

Could you help me to improve my coding style?:) In some tasks I need to check - is variable empty or contains something. To solve this task, I usually do the following.

检查-是否设置了此变量?如果已设置-我检查-它是否为空?

Check - is this variable set or not? If it's set - I check - it's empty or not?

<?php
    $var = '23';
    if (isset($var)&&!empty($var)){
        echo 'not empty';
    }else{
        echo 'is not set or empty';
    }
?>

我有一个问题-我应该在empty()之前使用isset()-是否有必要? TIA!

And I have a question - should I use isset() before empty() - is it necessary? TIA!

推荐答案

这取决于您要查找的内容,如果您只是想查看它是否为空,请使用empty,因为它还会检查是否已设置,如果您想知道是否设置了某些内容,请使用isset.

It depends what you are looking for, if you are just looking to see if it is empty just use empty as it checks whether it is set as well, if you want to know whether something is set or not use isset.

Empty检查是否设置了变量,是否设置为null,",0等

Empty checks if the variable is set and if it is it checks it for null, "", 0, etc

Isset只是检查是否已设置,可能不是空值

Isset just checks if is it set, it could be anything not null

对于empty,以下内容被认为是空的:

With empty, the following things are considered empty:

  • "(一个空字符串)
  • 0(0为整数)
  • 0.0(浮点数为0)
  • "0"(0作为字符串)
  • NULL
  • array()(一个空数组)
  • var $ var; (已声明的变量,但在类中没有值)

来自 http://php.net/manual/en/function.empty.php

如评论中所述,对于empty(),缺少警告也很重要

As mentioned in the comments the lack of warning is also important with empty()

PHP手册

empty()与(boolean)var相反,除了没有警告是 .

empty() is the opposite of (boolean) var, except that no warning is generated when the variable is not set.

关于isset

PHP手册

如果测试已设置为NULL的变量,

isset()将返回FALSE

isset() will return FALSE if testing a variable that has been set to NULL


您的代码可以满足以下要求:


Your code would be fine as:

<?php
    $var = '23';
    if (!empty($var)){
        echo 'not empty';
    }else{
        echo 'is not set or empty';
    }
?>


例如:


For example:

$var = "";

if(empty($var)) // true because "" is considered empty
 {...}
if(isset($var)) //true because var is set 
 {...}

if(empty($otherVar)) //true because $otherVar is null
 {...}
if(isset($otherVar)) //false because $otherVar is not set 
 {...}

这篇关于isset()和empty()-使用什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆