PHP quot;If truequot; test on array always returns true?(PHP“如果为真对数组的测试总是返回 true?)
问题描述
我有一个验证函数,如果验证通过,我想返回 true,如果验证失败,我想返回一个错误数组.但是,当我检查函数是否返回 true 时,即使返回值是数组,它也会返回 true.为什么是这样?作为我的意思的另一个例子:
I have a validation function that I want to return true if the validation passes, or an array of errors if validation fails. However, when I check if the function returns true, it returns true even if the returned value is an array. Why is this? As a further example of what I mean:
$array = ['test' => 'test'];
if ($array == true)
{
echo 'true';
}
我也尝试了同样的字符串:
and I also tried the same with a string:
$string = 'string';
if ($string == true)
{
echo 'true';
}
两者都回显真实.
这是为什么?如果我们能做到这一点,那我们为什么需要 isset() 函数呢?
Why is this? And if we can do this then why do we need the isset() function?
推荐答案
这是手册中记录的预期行为 http://php.net/manual/en/types.comparisons.php
This is expected behavior as documented in the manual http://php.net/manual/en/types.comparisons.php
Expression gettype() empty() is_null() isset() boolean
-----------------------------------------------------------------------
$x = array(); array TRUE FALSE TRUE FALSE
$x = array('a', 'b'); array FALSE FALSE TRUE TRUE
$x = ""; string TRUE FALSE TRUE FALSE
$x = "php"; string FALSE FALSE TRUE TRUE
因此,空字符串或数组的计算结果为 false,非空字符串或数组的计算结果为 true.
So an empty string or array will evaluate to false and non empty strings or arrays will evaluate to true.
另一方面,isset() 将确定是否定义了一个变量,而不管它的实际值如何.唯一不同的值是 null.如果使用 isset() 测试,值为 null 的变量将返回 false.
On the other hand isset() will determine if a variable is defined regardless of it's actual value. The only value being somehow different is null. A variable with value null will return false if tested with isset().
这篇关于PHP“如果为真"对数组的测试总是返回 true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP“如果为真"对数组的测试总是返回 true?
基础教程推荐
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 如何替换eregi() 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
