我应该在哪里使用 isset() 和 !empty()

发布于 2024-07-30 03:18:49 字数 491 浏览 6 评论 0原文

我在某处读到, isset() 函数将空字符串视为 TRUE,因此 isset() 不是验证文本输入的有效方法和 HTML 表单中的文本框。

因此,您可以使用 empty() 来检查用户是否输入了某些内容。

  1. isset() 函数是否将空字符串视为 TRUE

  2. 那么什么情况下应该使用isset()呢? 我应该总是使用 !empty() 来检查是否有东西吗?

例如,不要

if(isset($_GET['gender']))...

使用这个

if(!empty($_GET['gender']))...

I read somewhere that the isset() function treats an empty string as TRUE, therefore isset() is not an effective way to validate text inputs and text boxes from a HTML form.

So you can use empty() to check that a user typed something.

  1. Is it true that the isset() function treats an empty string as TRUE?

  2. Then in which situations should I use isset()? Should I always use !empty() to check if there is something?

For example instead of

if(isset($_GET['gender']))...

Using this

if(!empty($_GET['gender']))...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(20

提笔落墨 2024-08-06 03:18:50

isset() 测试变量是否已设置且不为空:

http://us .php.net/manual/en/function.isset.php

当变量设置为某些值时,empty() 可以返回 true:

http://us.php.net/manual/en/function.empty.php

<?php

$the_var = 0;

if (isset($the_var)) {
  echo "set";
} else {
  echo "not set";
}

echo "\n";

if (empty($the_var)) {
  echo "empty";
} else {
  echo "not empty";
}
?>

isset() tests if a variable is set and not null:

http://us.php.net/manual/en/function.isset.php

empty() can return true when the variable is set to certain values:

http://us.php.net/manual/en/function.empty.php

<?php

$the_var = 0;

if (isset($the_var)) {
  echo "set";
} else {
  echo "not set";
}

echo "\n";

if (empty($the_var)) {
  echo "empty";
} else {
  echo "not empty";
}
?>
对风讲故事 2024-08-06 03:18:50
    $var = '';
// Evaluates to true because $var is empty
if ( empty($var) ) {
echo '$var is either 0, empty, or not set at all';
}
// Evaluates as true because $var is set
if ( isset($var) ) {
 echo '$var is set even though it is empty';
    }

来源:PHP.net

    $var = '';
// Evaluates to true because $var is empty
if ( empty($var) ) {
echo '$var is either 0, empty, or not set at all';
}
// Evaluates as true because $var is set
if ( isset($var) ) {
 echo '$var is set even though it is empty';
    }

Source: Php.net

猫腻 2024-08-06 03:18:50

如有疑问,请使用此工具检查您的Value,并理清您的头脑,了解 issetempty 之间的区别。

if(empty($yourVal)) {
  echo "YES empty - $yourVal"; // no result
}
if(!empty($yourVal)) {
  echo "<P>NOT !empty- $yourVal"; // result
}
if(isset($yourVal)) {
  echo "<P>YES isset - $yourVal";  // found yourVal, but result can still be none - yourVal is set without value
}
if(!isset($yourVal)) {
  echo "<P>NO !isset - $yourVal"; // $yourVal is not set, therefore no result
}

When in doubt, use this one to check your Value and to clear your head on the difference between isset and empty.

if(empty($yourVal)) {
  echo "YES empty - $yourVal"; // no result
}
if(!empty($yourVal)) {
  echo "<P>NOT !empty- $yourVal"; // result
}
if(isset($yourVal)) {
  echo "<P>YES isset - $yourVal";  // found yourVal, but result can still be none - yourVal is set without value
}
if(!isset($yourVal)) {
  echo "<P>NO !isset - $yourVal"; // $yourVal is not set, therefore no result
}
爱的十字路口 2024-08-06 03:18:50

请考虑不同 PHP 版本上的行为可能会发生变化

来自文档

isset() 如果 var 存在并且具有 NULL 以外的任何值,则返回 TRUE。 否则为假
https://www.php.net/manual/en/function.isset。 php

empty() 不存在或者其值等于 FALSE
https://www.php.net/manual/en/function.empty。 php

(empty($x) == (!isset($x) || !$x)) // 返回 true;

(!empty($x) == (isset($x) && $x)) // 返回 true;

Please consider behavior may change on different PHP versions

From documentation

isset() Returns TRUE if var exists and has any value other than NULL. FALSE otherwise
https://www.php.net/manual/en/function.isset.php

empty() does not exist or if its value equals FALSE
https://www.php.net/manual/en/function.empty.php

(empty($x) == (!isset($x) || !$x)) // returns true;

(!empty($x) == (isset($x) && $x)) // returns true;

反差帅 2024-08-06 03:18:50

!empty 就可以了。 如果您只需要检查数据是否存在,那么使用 isset 其他 empty 可以处理其他验证

<?php
$array = [ "name_new" => "print me"];

if (!empty($array['name'])){
   echo $array['name'];
}

//output : {nothing}

////////////////////////////////////////////////////////////////////

$array2 = [ "name" => NULL];

if (!empty($array2['name'])){
   echo $array2['name'];
}

//output : {nothing}

////////////////////////////////////////////////////////////////////

$array3 = [ "name" => ""];

if (!empty($array3['name'])){
   echo $array3['name'];
}

//output : {nothing}  

////////////////////////////////////////////////////////////////////

$array4 = [1,2];

if (!empty($array4['name'])){
   echo $array4['name'];
}

//output : {nothing}

////////////////////////////////////////////////////////////////////

$array5 = [];

if (!empty($array5['name'])){
   echo $array5['name'];
}

//output : {nothing}

?>

!empty will do the trick. if you need only to check data exists or not then use isset other empty can handle other validations

<?php
$array = [ "name_new" => "print me"];

if (!empty($array['name'])){
   echo $array['name'];
}

//output : {nothing}

////////////////////////////////////////////////////////////////////

$array2 = [ "name" => NULL];

if (!empty($array2['name'])){
   echo $array2['name'];
}

//output : {nothing}

////////////////////////////////////////////////////////////////////

$array3 = [ "name" => ""];

if (!empty($array3['name'])){
   echo $array3['name'];
}

//output : {nothing}  

////////////////////////////////////////////////////////////////////

$array4 = [1,2];

if (!empty($array4['name'])){
   echo $array4['name'];
}

//output : {nothing}

////////////////////////////////////////////////////////////////////

$array5 = [];

if (!empty($array5['name'])){
   echo $array5['name'];
}

//output : {nothing}

?>

难理解 2024-08-06 03:18:50

以下对两个 php 结构的使用将帮助您选择最适合您情况的结构。

短篇故事

empty 检查变量是否已设置/定义,如果是,则检查它是否为 null,false, "", 0 。

isset 只是检查是否已设置,它可以是任何非 null

长话短说

isset< /code> 验证变量是否已定义并保存任何值,该值可以是任何不为空的值。

另一方面,empty 不仅检查变量是否已设置,还检查它是否包含被视为“空”的值,例如 null(空字符串) ''false0

The following use for the two php constructs will help you choose the best fit in your case.

Short story

empty checks if the variable is set/defined and if it is it checks it for null,false, "", 0.

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

Long story

The isset verifies if a variable has been defined and holds any value, the value could be anything not null.

On the other hand, empty not only checks if the variable is set but also examines if it contains a value that is considered "empty," such as null, an empty string '',false, or 0.

梦里南柯 2024-08-06 03:18:49

isset() 检查变量是否有
值,包括 False0 或空
字符串,但不包括 NULL。 返回真
如果 var 存在且不为 NULL; 否则为假。

empty() 与 isset 所做的相反(即 !isset()),并进行额外检查,以确定值是否为包含空字符串的“空” , 0, NULL, false, 或空数组或对象
错误的。 如果 var 已设置并且具有非空且非零值,则返回 FALSE。 否则为真

isset() checks if a variable has a
value, including False, 0 or empty
string, but not including NULL. Returns TRUE
if var exists and is not NULL; FALSE otherwise.

empty() does a reverse to what isset does (i.e. !isset()) and an additional check, as to whether a value is "empty" which includes an empty string, 0, NULL, false, or empty array or object
False. Returns FALSE if var is set and has a non-empty and non-zero value. TRUE otherwise

百变从容 2024-08-06 03:18:49

这都不是检查有效输入的好方法。

  • isset() 是不够的,因为 - 正如已经指出的 - 它认为空字符串是有效值。
  • <代码>! empty() 也是不够的,因为它拒绝“0”,而“0”可能是一个有效值。

使用 isset() 结合对空字符串的相等性检查是验证传入参数是否具有值而不产生误报所需的最低限度:

if( isset($_GET['gender']) and ($_GET['gender'] !== '') )
{
  ...
}

但我所说的“最低限度”是指正是如此。 上面的代码所做的只是确定 $_GET['gender'] 是否有某个值。 它确定$_GET['gender']的值是否有效(例如,("Male" , "女",“FileNotFound”<代码>))。

为此,请参阅乔什·戴维斯的回答

Neither is a good way to check for valid input.

  • isset() is not sufficient because – as has been noted already – it considers an empty string to be a valid value.
  • ! empty() is not sufficient either because it rejects '0', which could be a valid value.

Using isset() combined with an equality check against an empty string is the bare minimum that you need to verify that an incoming parameter has a value without creating false negatives:

if( isset($_GET['gender']) and ($_GET['gender'] !== '') )
{
  ...
}

But by "bare minimum", I mean exactly that. All the above code does is determine whether there is some value for $_GET['gender']. It does not determine whether the value for $_GET['gender'] is valid (e.g., one of ("Male", "Female","FileNotFound")).

For that, see Josh Davis's answer.

魂归处 2024-08-06 03:18:49

isset 仅用于变量而不仅仅是值,因此 < code>isset("foobar") 将引发错误。 从 PHP 5.5 开始,empty 支持变量和表达式。

因此,您的第一个问题应该是 isset 对于包含空字符串的变量是否返回 true。 答案是:

$var = "";
var_dump(isset($var));

PHP手册中的类型比较表非常方便对于这样的问题。

isset 基本上检查变量是否具有除 null 之外的任何值,因为不存在的变量始终具有值 nullemptyisset 的对应部分,但也处理整数值 0 和字符串值 "0"为空。 (再次查看类型比较表。)

isset is intended to be used only for variables and not just values, so isset("foobar") will raise an error. As of PHP 5.5, empty supports both variables and expressions.

So your first question should rather be if isset returns true for a variable that holds an empty string. And the answer is:

$var = "";
var_dump(isset($var));

The type comparison tables in PHP’s manual is quite handy for such questions.

isset basically checks if a variable has any value other than null since non-existing variables have always the value null. empty is kind of the counter part to isset but does also treat the integer value 0 and the string value "0" as empty. (Again, take a look at the type comparison tables.)

怀念你的温柔 2024-08-06 03:18:49

最一般的方式:

  • isset 测试变量(或数组或对象的属性)存在(且不为空)
  • 空< /code>测试变量是否未设置或包含类似空的值。

回答问题 1

$str = '';
var_dump(isset($str));

给出

boolean true

因为变量 $str 存在。

问题2

您应该使用isset来判断变量是否存在; 例如,如果您以数组形式获取一些数据,则可能需要检查该数组中是否设置了某个键(并且其值不为空)。

例如,考虑 $_GET / $_POST

如果你想知道一个变量是否存在并且不是“空”,那就是empty的工作。

In the most general way :

  • isset tests if a variable (or an element of an array, or a property of an object) exists (and is not null)
  • empty tests if a variable is either not set or contains an empty-like value.

To answer question 1 :

$str = '';
var_dump(isset($str));

gives

boolean true

Because the variable $str exists.

And question 2 :

You should use isset to determine whether a variable exists; for instance, if you are getting some data as an array, you might need to check if a key is set in that array (and its value is not null).

Think about $_GET / $_POST, for instance.

If you want to know whether a variable exists and not "empty", that is the job of empty.

盗梦空间 2024-08-06 03:18:49

如果您有 $_POST['param'] 并假设它是字符串类型,那么

isset($_POST['param']) && $_POST['param'] != ''

!empty($_POST['param'])

If you have a $_POST['param'] and assume it's string type then

isset($_POST['param']) && $_POST['param'] != ''

is identical to

!empty($_POST['param'])
这样的小城市 2024-08-06 03:18:49

isset() vs empty() vs is_null()

在此处输入图像描述

isset() vs empty() vs is_null()

enter image description here

梦太阳 2024-08-06 03:18:49

何时以及如何使用:

  1. isset()

True 表示 0、1、空字符串、包含值的字符串、true、false

False 未定义变量表示 null

,例如

$status = 0
if (isset($status)) // True
$status = null 
if (isset($status)) // False
  1. Empty

False 表示 1,包含值的字符串,true

True 表示未定义值,null,空字符串,0,false
例如

$status = 0
if(empty($status)) // true
$status = 1
if(empty($status)) // False

When and how to use:

  1. isset()

True for 0, 1, empty string, a string containing a value, true, false

False undefined variable for null

e.g

$status = 0
if (isset($status)) // True
$status = null 
if (isset($status)) // False
  1. Empty

False for 1, a string containing a value, true

True for undefined value, null, empty string, 0, false
e.g

$status = 0
if(empty($status)) // true
$status = 1
if(empty($status)) // False
一梦浮鱼 2024-08-06 03:18:49

isset() 不是验证 HTML 表单中的文本输入和文本框的有效方法

您可以将其重写为“isset() 不是验证输入的方法。”要验证输入,请使用 PHP 的过滤器扩展filter_has_var() 将告诉您变量是否存在,而 filter_input() 将实际过滤和/或清理输入。

请注意,您不必在 filter_input() 之前使用 filter_has_var(),如果您请求未设置的变量,则使用 filter_input()< /code> 将简单地返回 null

isset() is not an effective way to validate text inputs and text boxes from a HTML form

You can rewrite that as "isset() is not a way to validate input." To validate input, use PHP's filter extension. filter_has_var() will tell you whether the variable exists while filter_input() will actually filter and/or sanitize the input.

Note that you don't have to use filter_has_var() prior to filter_input() and if you ask for a variable that is not set, filter_input() will simply return null.

记忆之渊 2024-08-06 03:18:49
isset($variable) === (@$variable !== null)
empty($variable) === (@$variable == false)
isset($variable) === (@$variable !== null)
empty($variable) === (@$variable == false)
城歌 2024-08-06 03:18:49

isset 用于确定某事物的实例是否存在,即变量是否已实例化...它不关心参数的值...

Pascal MARTIN... +1
...

如果变量不存在,empty() 不会生成警告...因此,当您打算修改变量时测试变量是否存在时,首选 isset()...

isset is used to determine if an instance of something exists that is, if a variable has been instantiated... it is not concerned with the value of the parameter...

Pascal MARTIN... +1
...

empty() does not generate a warning if the variable does not exist... therefore, isset() is preferred when testing for the existence of a variable when you intend to modify it...

雨落□心尘 2024-08-06 03:18:49

isset() 用于检查变量是否设置了值,Empty() 用于检查给定变量是否为空。

当变量不为 null 时,isset() 返回 true,而如果变量为空字符串,则 Empty() 返回 true。

isset() is used to check if the variable is set with the value or not and Empty() is used to check if a given variable is empty or not.

isset() returns true when the variable is not null whereas Empty() returns true if the variable is an empty string.

不知所踪 2024-08-06 03:18:49

我来这里寻找一种快速方法来检查变量中是否有任何内容。 这里的答案都没有提供完整的解决方案,所以这里是:


检查输入是否为 ''null 就足够了,因为:

请求 URL 。 ../test.php?var= 结果 $_GET['var'] = ''

请求 URL .../test.php 结果$_GET['var'] = null


isset() 仅当变量存在且未设置为 null< 时才返回 false /code>,因此如果您使用它,您将获得空字符串 ('') 的 true

empty() 认为 null'' 都为空,但它也认为 '0' 为空,即在某些用例中存在问题。

如果您想将 '0' 视为空,请使用 empty()。 否则,请使用以下检查:

仅对于以下输入,$var .'' !== '' 计算结果为 false

  • ''
  • null
  • false

我使用以下检查来过滤掉仅包含空格和换行符的字符串:

function hasContent($var){
    return trim($var .'') !== '';
}

I came here looking for a quick way to check if a variable has any content in it. None of the answers here provided a full solution, so here it is:


It's enough to check if the input is '' or null, because:

Request URL .../test.php?var= results in $_GET['var'] = ''

Request URL .../test.php results in $_GET['var'] = null


isset() returns false only when the variable exists and is not set to null, so if you use it you'll get true for empty strings ('').

empty() considers both null and '' empty, but it also considers '0' empty, which is a problem in some use cases.

If you want to treat '0' as empty, then use empty(). Otherwise use the following check:

$var .'' !== '' evaluates to false only for the following inputs:

  • ''
  • null
  • false

I use the following check to also filter out strings with only spaces and line breaks:

function hasContent($var){
    return trim($var .'') !== '';
}
街角卖回忆 2024-08-06 03:18:49

使用 empty 就足够了:

if(!empty($variable)){
    // Do stuff
}

此外,如果您想要一个整数值,也可能值得检查 intval($variable) !== FALSE

Using empty is enough:

if(!empty($variable)){
    // Do stuff
}

Additionally, if you want an integer value it might also be worth checking that intval($variable) !== FALSE.

别挽留 2024-08-06 03:18:49

我使用以下内容来避免通知,这会检查 var 是否在 GET 或 POST 上声明,并且使用 @ 前缀,您可以安全地检查是否不为空,并在未设置 var 时避免通知:

if( isset($_GET['var']) && @$_GET['var']!='' ){
    //Is not empty, do something
}

I use the following to avoid notices, this checks if the var it's declarated on GET or POST and with the @ prefix you can safely check if is not empty and avoid the notice if the var is not set:

if( isset($_GET['var']) && @$_GET['var']!='' ){
    //Is not empty, do something
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文