Is array considered boolean true in php?

I have a quick question. I know that the cakePHP find ('first') function returns an array containing the first result, if found, false otherwise. My question is, if I have to write a check, for example:

if(result_is_array) // that means I have data { // do something } else // that means result is a boolean { // do something else } 

Instead of checking if the result from find('first') array or not, can I just say:

 $result = $this->MyModel->find('first'); if($result) { // do something } 

In the case of words, if I get the array here, will it be evaluated using TRUE in php? Is if(array()) equal to TRUE in php?

+4
source share
6 answers

YES you can do

 $result = $this->MyModel->find('first'); if($result) 

An array with length > 0 returns true

The explanation is given in the docs.

When converting to boolean, the following values ​​are considered FALSE

  • array with zero elements

Every other value counts as TRUE.

+7
source

Instead of checking if 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 fail.

The best part of this is done this way: it makes the reader understand that you are checking a non-empty value.

+2
source

Array of zero value false

An array with values ​​in it true

You can look at this table to see what evaluates to true vs false .

+1
source

According to the documentation , if you try to treat the array as a boolean, the array will be considered true when it is not empty.

+1
source

An empty array will always evaluate to false, or if it contains any keys / values, then it will evaluate to true. if $this->MyModel->find('first'); always returns an array, then an empty result will be evaluated as false and true to others. so your code works fine.

0
source

Use the following if you are looking for a TRUE value:

 if ( $result !== false ) { // do something } 
0
source

Source: https://habr.com/ru/post/1403119/


All Articles