[英]Is an array considered as boolean true in php?
I have a quick question here. 我在这里有一个简单的问题。 I know that the cakePHP find('first') function returns an array containing the first result if found, false otherwise.
我知道cakePHP find('first')函数返回一个包含第一个结果的数组(如果找到),否则返回false。 My question is this, what if I were to write a check like this:
我的问题是,如果我写这样的支票怎么办:
if(result_is_array) // that means I have data
{
// do something
}
else // that means result is a boolean
{
// do something else
}
Instead of checking whether the result obtained from find('first')
is an array or not, can I just say: 我可以这样说,而不是检查从
find('first')
获得的结果是否是数组?
$result = $this->MyModel->find('first');
if($result)
{
// do something
}
In order words, if I get an array here, will that evaluate to TRUE
in php? 顺便说一句,如果我在这里获得一个数组,那么在php中评估为
TRUE
吗? Is if(array())
equal to true
in php? if(array())
在php中是否等于true
?
YES you can do 是的,你可以做到
$result = $this->MyModel->find('first');
if($result)
An array with length > 0
returns true
length > 0
的数组返回true
Explanation is here in the docs 解释在这里的文档中
When converting to boolean, the following values are considered FALSE
转换为布尔值时,以下值被视为FALSE
- an array with zero elements
一个零元素的数组
Every other value is considered TRUE
其他每个值都被视为TRUE
Instead of checking whether the result obtained from find('first') is an array or not
而不是检查从find('first')获得的结果是否是数组
Yes. 是。 Do it the second way:
if ($result)
. 第二种方式:
if ($result)
。 If find
returns an empty array or boolean false
, the branch will not be executed. 如果
find
返回一个空数组或布尔false
,则不会执行该分支。
The best part about doing it this way is that it makes it clear to the reader that you are checking for a non-empty value. 以这种方式执行此操作的最佳部分是, 它使读者清楚您正在检查非空值。
A zero value array is false
零值数组为
false
An array with values in it is true
包含值的数组为
true
You can view this table to see what is evaluated as true
vs false
. 您可以查看此表以查看评估为
true
和false
。
根据文档 ,如果您尝试将数组视为布尔值,则数组在非空时将被视为真。
An empty array will always evaluate to false or if it contain any key/values then it will evaluate to true. 空数组将始终求值为false,或者如果它包含任何键/值,则它将计算为true。 if
$this->MyModel->find('first');
如果
$this->MyModel->find('first');
always returns an array then an empty result will evaluate to false and true other wise. 总是返回一个数组,然后一个空结果将评估为false,而其他方面则为true。 so your code is perfectly valid.
所以你的代码是完全有效的。
Use the following if you are looking for a TRUE
value: 如果您要查找
TRUE
值,请使用以下内容:
if ( $result !== false )
{
// do something
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.