问题描述
我有一个验证函数,如果验证通过,我想返回 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!