检查“不为空”或空字符串的 PHP 语法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11213125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:59:51  来源:igfitidea点击:

What is the PHP syntax to check "is not null" or an empty string?

phpvariablesnullconditional-statements

提问by I wrestled a bear once.

Possible Duplicate:
Check if a variable is empty

可能的重复:
检查变量是否为空

Simple PHP question:

简单的 PHP 问题:

I have this stement:

我有这个词干:

if (isset($_POST["password"]) && ($_POST["password"]=="$password")) {
...//IF PASSWORD IS CORRECT STUFF WILL HAPPEN HERE
}

Somewhere above this statement I use the following line in my JavaScript to set the username as a variable both in my JavaScript and in my PHP:

在此语句上方的某处,我在 JavaScript 中使用以下行将用户名设置为 JavaScript 和 PHP 中的变量:

uservariable = <?php $user = $_POST['user']; print ("\"" . $user . "\"")?>;

What I want to do is add a condition to make sure $user is not null or an empty string (it doesn't have to be any particular value, I just don't want it to be empty. What is the proper way to do this?

我想要做的是添加一个条件以确保 $user 不是 null 或空字符串(它不必是任何特定的值,我只是不希望它为空。正确的方法是什么?做这个?

I know this is a sill question but I have no experience with PHP. Please advise, Thank you!

我知道这是一个sill 问题,但我没有PHP 的经验。请指教,谢谢!

回答by John Green

Null OR an empty string?

Null 或空字符串?

if (!empty($user)) {}

Use empty().

使用空()。



After realizing that $user ~= $_POST['user'] (thanks matt):

在意识到 $user ~= $_POST['user'] 之后(感谢 matt):

var uservariable='<?php 
    echo ((array_key_exists('user',$_POST)) || (!empty($_POST['user']))) ? $_POST['user'] : 'Empty Username Input';
?>';

回答by John Conde

Use empty(). It checks for both empty strings and null.

使用empty(). 它检查空字符串和空字符串。

if (!empty($_POST['user'])) {
  // do stuff
}

From the manual:

从手册:

The following things are considered to be empty:

以下内容被认为是空的:

"" (an empty string)  
0 (0 as an integer)  
0.0 (0 as a float)  
"0" (0 as a string)    
NULL  
FALSE  
array() (an empty array)  
var $var; (a variable declared, but without a value in a class)