Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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?

like image 541
user765368 Avatar asked Mar 23 '12 16:03

user765368


1 Answers

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

like image 82
Manse Avatar answered Nov 02 '22 01:11

Manse