'0' PHP 中使用 empty() 作为字符串

发布于 2024-10-01 14:55:10 字数 221 浏览 5 评论 0原文

我希望将 0 视为整数,将 '0' 视为字符串,但在下面的示例中,empty() 将 '0' 视为字符串,

$var = '0';

// Evaluates to true because $var is empty
if (empty($var)) {
    echo '$var is empty';
}

我如何“使”empty() 采取'0 作为字符串?

I want a 0 to be considered as an integer and a '0' to be considered as a string, but empty() considers the '0' as a string in the example below,

$var = '0';

// Evaluates to true because $var is empty
if (empty($var)) {
    echo '$var is empty';
}

How can I 'make' empty() to take '0's as strings?

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

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

发布评论

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

评论(12

臻嫒无言 2024-10-08 14:55:10

你不能让empty()接受它。它就是这样设计的。相反,您可以编写一个 and 语句来测试:

if (empty($var) && $var !== '0') {
    echo $var . ' is empty';
}

您可以使用 isset,当然,除非您希望它拒绝其他 empty 的空容器> 检查。

You cannot make empty() take it. That is how it was designed. Instead you can write an and statement to test:

if (empty($var) && $var !== '0') {
    echo $var . ' is empty';
}

You could use isset, unless of course, you want it to turn away the other empties that empty checks for.

柏林苍穹下 2024-10-08 14:55:10

您不能使用来自 PHP 手册:

以下内容被视为空:

  • ""(空字符串)
  • 0(0 作为整数)
  • “0”(0 作为字符串)
  • 错误
  • array()(空数组)
  • var $var; (声明了一个变量,但在类中没有值)

您必须添加额外的其他检查。

You cannot with empty. From the PHP Manual:

The following things are considered to be empty:

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

You have to add an additional other check.

瀞厅☆埖开 2024-10-08 14:55:10

PHP 有不同的函数可用于测试变量的值。三个有用的函数是 isset()empty()is_null()。所有这些函数都返回一个布尔值。如果这些功能没有以正确的方式使用,可能会导致意想不到的结果。

isset() 和empty() 通常被视为相反的函数,但事实并非总是如此。在这篇文章中,我将解释这些函数之间的差异。

isset()

摘自 PHP 手册 – isset()

isset — 确定变量是否已设置且不为 NULL

换句话说,仅当变量不为 null 时才返回 true。
empty()

摘自 PHP 手册 –empty()

empty — 判断变量是否为空

,也就是说,如果变量是空字符串,则返回 true,如果为 false,则返回 array()、NULL、“0?”、0、未设置的变量。
is_null()

摘自 PHP 手册 – is_null()

is_null — 查找变量是否为 NULL

换句话说,仅当变量为 null 时才返回 true。 is_null() 与 isset() 相反,除了 isset() 可以应用于未知变量,而 is_null() 只能应用于已声明的变量。

图中的表格是这些函数针对不同值将返回的内容的简单参考。空格表示函数返回 bool (false)。

输入图片这里的描述

此外,我还制作了一个自定义函数来检查所有内容:

function checkEmpty($var, $term = ""){
    if(isset($var) && trim($var) != "" && (!empty($var) || trim($var) == 0)){
        return true;
    }
    else{
        if($term != ""){
            return array("status" => "error", "desc" => "$term can not be empty");
        }
        else{
            return array("status" => "error", "desc" => "value can not be empty");
        }
    }
}

PHP has different functions which can be used to test the value of a variable. Three useful functions for this are isset(), empty(), and is_null(). All these function return a boolean value. If these functions are not used in correct way they can cause unexpected results.

isset() and empty() are often viewed as functions that are opposite, however this is not always true. In this post I will explain the differences between these functions.

isset()

From PHP manual – isset():

isset — Determine if a variable is set and is not NULL

In other words, it returns true only when the variable is not null.
empty()

From PHP Manual – empty():

empty — Determine whether a variable is empty

In other words, it will return true if the variable is an empty string, false, array(), NULL, “0?, 0, and an unset variable.
is_null()

From PHP Manual – is_null():

is_null — Finds whether a variable is NULL

In other words, it returns true only when the variable is null. is_null() is opposite of isset(), except for one difference that isset() can be applied to unknown variables, but is_null() only to declared variables.

The table in picture is an easy reference for what these functions will return for different values. The blank spaces means the function returns bool (false).

Enter image description here

Also I have made a custom function for checking all stuff:

function checkEmpty($var, $term = ""){
    if(isset($var) && trim($var) != "" && (!empty($var) || trim($var) == 0)){
        return true;
    }
    else{
        if($term != ""){
            return array("status" => "error", "desc" => "$term can not be empty");
        }
        else{
            return array("status" => "error", "desc" => "value can not be empty");
        }
    }
}
似狗非友 2024-10-08 14:55:10

你不能只用empty()。请参阅手册。不过,您可以这样做:

if ($var !== '0' && empty($var)) {
   echo "$var is empty and is not string '0'";
}

基本上,empty() 的作用与:

if (!$var) ...

但当未设置变量时,它不会触发 PHP 通知

You can't with only empty(). See the manual. You can do this though:

if ($var !== '0' && empty($var)) {
   echo "$var is empty and is not string '0'";
}

Basically, empty() does the same as:

if (!$var) ...

But it doesn't trigger a PHP notice when the variable is not set.

始终不够 2024-10-08 14:55:10

你不能。来自手册

如果 var 具有非空且非零值,则返回 FALSE。

以下内容被视为空:

  • ""(空字符串)
  • 0(0 作为整数)
  • “0”(0 作为字符串)
  • 错误
  • array()(空数组)
  • var $var; (声明了一个变量,但在类中没有值)

You can't. From the manual

Returns FALSE if var has a non-empty and non-zero value.

The following things are considered to be empty:

  • "" (an empty string)
  • 0 (0 as an integer)
  • "0" (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • var $var; (a variable declared, but without a value in a class)
孤蝉 2024-10-08 14:55:10

empty 是 PHP 函数库中迄今为止最令人困惑和无用的函数。不要使用它。

检查值时您需要了解三件不同的事情。

  • 值存在(使用 isset)
  • 值具有特定类型(使用 is_xxx)
  • 值具有特定属性(使用比较运算符、strpos 或正则表达式)。

(最后两个可以通过类型转换或“===”组合成一个)。

示例:

if(isset($var) && is_string($var) && strlen($var) > 0)...
if(isset($var) && intval($var) > 0)...
if(isset($var) && $var === '0')...

这看起来更冗长,但它清楚地显示了您在做什么。对于结构对象来说,有一个快捷方式 getter 通常是有意义的,例如

 /// Get a string
 function s($ary, $key, $default = '') {
     if(!isset($ary[$key])) return $default;
     $s = trim($ary[$key]);
     return strlen($s) ? $s : $default;
 }
 /// Get a natural number
 function n($ary, $key, $default = 0) {
     $n = intval(s($ary, $key));
     return $n > 0 ? $n : $default;
 }

 $name = s($_POST, 'name');
 $age  = n($_POST, 'age');

empty is by far the most confusing and useless function in the PHP repertoire. Don't use it.

There are three separate things you want to know when checking a value.

  • the value exists (use isset)
  • the value has a specific type (use is_xxx)
  • the value has specific properties (use comparison operators, strpos or regular expressions).

(the last two can be combined into one with typecasts or '===').

Examples:

if(isset($var) && is_string($var) && strlen($var) > 0)...
if(isset($var) && intval($var) > 0)...
if(isset($var) && $var === '0')...

This seems more verbose, but it shows clearly what you're doing. For structural objects it often makes sense to have a shortcut getter, e.g.

 /// Get a string
 function s($ary, $key, $default = '') {
     if(!isset($ary[$key])) return $default;
     $s = trim($ary[$key]);
     return strlen($s) ? $s : $default;
 }
 /// Get a natural number
 function n($ary, $key, $default = 0) {
     $n = intval(s($ary, $key));
     return $n > 0 ? $n : $default;
 }

 $name = s($_POST, 'name');
 $age  = n($_POST, 'age');
掩饰不了的爱 2024-10-08 14:55:10

在这两种情况下,empty() 都会返回true。检查文档

我建议使用不同的函数来匹配您的规格。

In both of your cases empty() will return true. Check the documentation.

I suggest using a different function to match your specification.

不如归去 2024-10-08 14:55:10
$var = '0';

// Evaluates to true because $var is empty
if (empty($var) && $var !== '0') {
    echo '$var is empty or the string "0"';
}
$var = '0';

// Evaluates to true because $var is empty
if (empty($var) && $var !== '0') {
    echo '$var is empty or the string "0"';
}
假装爱人 2024-10-08 14:55:10

我总是将其添加到我的代码库中:

function is_blank($value) {
    return empty($value) && !is_numeric($value);
}

并使用它而不是empty()。它解决了将零(整数、浮点数或字符串)保持为非空的问题。

请参阅 2011 年 5 月添加的 is_blank()

I always add this to my codebase:

function is_blank($value) {
    return empty($value) && !is_numeric($value);
}

And use it instead of empty(). It solves the issue of keeping zeros (int, float or string) as non-empty.

See is_blank() which was added May 2011.

为你拒绝所有暧昧 2024-10-08 14:55:10

如果您想跳过空 $filter 并且不跳过 $filter = '0' 和其他值:

$filter = ''; // Or $filter = '0'; or $filter = '1';

// Trim the $filter

if(isset($filter) and ($filter != '' or $filter == '0')) {

    // $filter data

};

If you want skip an empty $filter and don’t skip $filter = '0' and other values:

$filter = ''; // Or $filter = '0'; or $filter = '1';

// Trim the $filter

if(isset($filter) and ($filter != '' or $filter == '0')) {

    // $filter data

};
仙女山的月亮 2024-10-08 14:55:10

在这种情况下,不要使用empty()。使用 isset() 代替它。这也将允许 0 作为整数。

$var = '0';
if (!isset($var)) {
    print '$var is not set';
}

$var = 0;
if (!isset($var)) {
    print '$var is not set';
}

两者都不应该打印任何东西。

In this case, don't use empty(). Use isset() in place of it. This will also allow 0 as an integer.

$var = '0';
if (!isset($var)) {
    print '$var is not set';
}

$var = 0;
if (!isset($var)) {
    print '$var is not set';
}

Neither should print anything.

苦笑流年记忆 2024-10-08 14:55:10

不能,因为整数、字符串、浮点数和 null 对于 PHP 来说并不重要。

因为它很酷:)

您必须检查变量的特征: is_numeric (), isset(), === 、strlen()等例如

if (strlen(@$var)==0) {
    echo @$var . ' is empty';
}

if (@$var==="" || !isset($var)) {
    echo @$var . ' is empty';
}

或其他示例:)

You can not, because integer, string, float, and null do not matter for PHP.

Because it is cool :)

You must check characteristic features for your variable: is_numeric(), isset(), ===, strlen(), etc.

For example:

if (strlen(@$var)==0) {
    echo @$var . ' is empty';
}

or

if (@$var==="" || !isset($var)) {
    echo @$var . ' is empty';
}

or other examples :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文