问题
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. 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:
$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? Is if(array())
equal to true
in php?
回答1:
YES you can do
$result = $this->MyModel->find('first');
if($result)
An array with length > 0
returns true
Explanation is here in the docs
When converting to boolean, the following values are considered FALSE
- an array with zero elements
Every other value is considered TRUE
回答2:
Instead of checking whether the result obtained from find('first') is an array or not
Yes. Do it the second way:if ($result)
. If find
returns an empty array or boolean false
, the branch will not be executed.
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.
回答3:
A zero value array is false
An array with values in it is true
You can view this table to see what is evaluated as true
vs false
.
回答4:
According to the documentation, if you try to treat an array as a boolean, the array will be considered true precisely when it's not empty.
回答5:
Use the following if you are looking for a TRUE
value:
if ( $result !== false )
{
// do something
}
回答6:
An empty array will always evaluate to false or if it contain any key/values then it will evaluate to true. if $this->MyModel->find('first');
always returns an array then an empty result will evaluate to false and true other wise. so your code is perfectly valid.
来源:https://stackoverflow.com/questions/9843077/is-an-array-considered-as-boolean-true-in-php