isset vs empty vs is_null

后端 未结 14 2148
野的像风
野的像风 2020-11-29 08:34

I\'m trying to write a script that when a user uploads a file and does not enter a name an error is returned. I\'ve tried using is_null, empty, and isset and they all do not

14条回答
  •  一整个雨季
    2020-11-29 08:54

    PHP empty() vs is_null() vs isset():

                +-------+-------+-------+-------+-------+--------------+
                |  ""   | "foo" | NULL  | FALSE |   0   | undefined    |
    +-----------+-------+-------+-------+-------+-------+--------------+
    | empty()   | TRUE  | FALSE | TRUE  | TRUE  | TRUE  | TRUE         |
    | is_null() | FALSE | FALSE | TRUE  | FALSE | FALSE | TRUE (ERROR) |
    | isset()   | TRUE  | TRUE  | FALSE | TRUE  | TRUE  | FALSE        |
    +-----------+-------+-------+-------+-------+-------+--------------+
    

    If you want to check if there's any value other than null or undefined, use isset($var)
    (because !is_null() generates a warning on undefined variables.)

    If you want to check if the value is non-blank text or any number including zero, it gets trickier:

    if (!empty($v) || (isset($v) && ($v === 0 || $v === '0'))) {
        // $v is non-blank text, true, 0 or '0'
        // $v is NOT an empty string, null, false or undefined
    }
    

提交回复
热议问题