php 检查变量是否为空字符串或空字符串的更好方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/381265/
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
Better way to check variable for null or empty string?
提问by Allain Lalonde
Since PHP is a dynamic language what's the best way of checking to see if a provided field is empty?
由于 PHP 是一种动态语言,检查提供的字段是否为空的最佳方法是什么?
I want to ensure that:
我想确保:
- null is considered an empty string
- a white space only string is considered empty
- that "0" is not considered empty
- null 被认为是一个空字符串
- 只有空格的字符串被认为是空的
- “0”不被认为是空的
This is what I've got so far:
这是我到目前为止所得到的:
$question = trim($_POST['question']);
if ("" === "$question") {
// Handle error here
}
There must be a simpler way of doing this?
必须有一个更简单的方法来做到这一点?
回答by Michael Haren
// Function for basic field validation (present and neither empty nor only white space
function IsNullOrEmptyString($str){
return (!isset($str) || trim($str) === '');
}
回答by jrowe
Old post but someone might need it as I did ;)
旧帖子,但有人可能像我一样需要它;)
if (strlen($str) == 0){
do what ever
}
replace $strwith your variable.
NULLand ""both return 0 when using strlen.
替换$str为您的变量。
NULL并且""在使用时都返回 0 strlen。
回答by kta
Use PHP's empty() function. The following things are considered to be empty
使用 PHP 的 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; (a variable declared, but without a value)
For more details check empty function
有关更多详细信息,请检查空函数
回答by Adal
I'll humbly accept if I'm wrong, but I tested on my own end and found that the following works for testing both string(0) "" and NULL valued variables:
如果我错了,我会虚心接受,但我在自己的一端进行了测试,发现以下适用于测试 string(0) "" 和 NULL 值变量:
if ( $question ) {
// Handle success here
}
Which could also be reversed to test for success as such:
也可以反过来测试是否成功:
if ( !$question ) {
// Handle error here
}
回答by Ben Blank
Beware false negatives from the trim()function — it performs a cast-to-string before trimming, and thus will return e.g. "Array" if you pass it an empty array. That may not be an issue, depending on how you process your data, but with the code you supply, a field named question[]could be supplied in the POST data and appear to be a non-empty string. Instead, I would suggest:
当心trim()函数的误报——它在修剪之前执行转换为字符串,因此如果你传递一个空数组,它将返回例如“Array”。这可能不是问题,具体取决于您处理数据的方式,但使用您提供的代码,question[]可以在 POST 数据中提供一个名为的字段,并且看起来是一个非空字符串。相反,我建议:
$question = $_POST['question'];
if (!is_string || ($question = trim($question))) {
// Handle error here
}
// If $question was a string, it will have been trimmed by this point
回答by e-satis
There is no better way but since it's an operation you usually do quite often, you'd better automatize the process.
没有更好的方法,但由于这是您通常经常执行的操作,因此您最好将过程自动化。
Most frameworks offer a way to make arguments parsing an easy task. You can build you own object for that. Quick and dirty example :
大多数框架都提供了一种使参数解析成为一项简单任务的方法。您可以为此构建自己的对象。快速而肮脏的例子:
class Request
{
// This is the spirit but you may want to make that cleaner :-)
function get($key, $default=null, $from=null)
{
if ($from) :
if (isset(${'_'.$from}[$key]));
return sanitize(${'_'.strtoupper($from)}[$key]); // didn't test that but it should work
else
if isset($_REQUEST[$key])
return sanitize($_REQUEST[$key]);
return $default;
}
// basics. Enforce it with filters according to your needs
function sanitize($data)
{
return addslashes(trim($data));
}
// your rules here
function isEmptyString($data)
{
return (trim($data) === "" or $data === null);
}
function exists($key) {}
function setFlash($name, $value) {}
[...]
}
$request = new Request();
$question= $request->get('question', '', 'post');
print $request->isEmptyString($question);
Symfony use that kind of sugar massively.
Symfony 大量使用这种糖。
But you are talking about more than that, with your "// Handle error here ". You are mixing 2 jobs : getting the data and processing it. This is not the same at all.
但是你说的远不止这些,还有你的“//在这里处理错误”。您正在混合 2 个工作:获取数据并处理它。这根本不一样。
There are other mechanisms you can use to validate data. Again, frameworks can show you best pratices.
您可以使用其他机制来验证数据。同样,框架可以向您展示最佳实践。
Create objects that represent the data of your form, then attach processses and fall back to it. It sounds far more work that hacking a quick PHP script (and it is the first time), but it's reusable, flexible, and much less error prone since form validation with usual PHP tends to quickly become spaguetti code.
创建代表表单数据的对象,然后附加流程并回退到它。听起来比破解一个快速的 PHP 脚本(这是第一次)要工作得多,但它是可重用的、灵活的,而且不容易出错,因为使用通常的 PHP 进行表单验证往往很快就会变成意大利面条式的代码。
回答by Chris Clower
This one checks arrays andstrings:
这个检查数组和字符串:
function is_set($val) {
if(is_array($val)) return !empty($val);
return strlen(trim($val)) ? true : false;
}
回答by bcag2
to be more robust (tabulation, return…), I define:
为了更健壮(制表、返回……),我定义:
function is_not_empty_string($str) {
if (is_string($str) && trim($str, " \t\n\rfunction isSet($param)
{
return (is_array($param) && count($param)) || trim($param) !== '';
}
") !== '')
return true;
else
return false;
}
// code to test
$values = array(false, true, null, 'abc', '23', 23, '23.5', 23.5, '', ' ', '0', 0);
foreach ($values as $value) {
var_export($value);
if (is_not_empty_string($value))
print(" is a none empty string!\n");
else
print(" is not a string or is an empty string\n");
}
sources:
来源:
回答by PHPst
When you want to check if a value is provided for a field, that field may be a string, an array, or undifined. So, the following is enough
当您要检查是否为某个字段提供了值时,该字段可能是 a string、 anarray或 undifined。所以,以下就足够了
if (is_object($theObject) && (count(get_object_vars($theObject)) > 0)) {
回答by NJInamdar
empty() used to work for this, but the behavior of empty() has changed several times. As always, the php docs are always the best source for exact behavior and the comments on those pages usually provide a good history of the changes over time. If you want to check for a lack of object properties, a very defensive method at the moment is:
empty() 曾经为此工作,但 empty() 的行为已经改变了几次。与往常一样,php 文档始终是准确行为的最佳来源,这些页面上的评论通常会提供随时间变化的良好历史记录。如果要检查是否缺少对象属性,目前一个非常防御性的方法是:
##代码##
