简体   繁体   中英

Why Laravel return array not working with empty() But worked with count()

I am working with laravel framework project and facing below issue.

Query:

$query = DB::table('test');
$query->select('*');
$query->where('testId = 1');
$result = $query->get();
print_r($result);

Output :

Illuminate\Support\Collection Object
(
    [items:protected] => Array
        (
        )

)

Now I am checking $result have record or not.

if(empty($result))
{
   echo "Not Empty check with empty()";
}

if(count($result) == 0)
{
   echo "Not Empty check with count()";
}

Output:

Not Empty check with count()

Question :

I have used empty() in all the projects but in laravel framework project I am not able to know that why this $result going in count() condition and not going in empty() .

Note:

I have read that count() is slow compare to empty() also empty() check variable is set or not so I am using empty() in all return array or object array.

Please help someone.

Thanks in advance!

If you use collection, you sould use isEmpty() method

docs: https://laravel.com/docs/5.4/collections#method-isempty

From the php docs

Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE. empty() does not generate a warning if the variable does not exist.

The laravel collection class implements the Countable interface which lets you use the count function. If you check the collection class you'll see that the count method returns the count of the internal items.

There is no interface for the empty function so in this case it only checks if the variable is not set or equals to false which obvious doesn't apply in case an object is checked.

With ->get() method, you will get an instance of collection.

When you apply empty() on data obtained from get method, you'll notice an instance of Illuminate\\Support\\Collection is always returned, even when there are no results.

When you obtain data with ->get() method, you can't use following simply,

if(empty($data)){ 

}

if(!data){ 

}

if($data){ 

}

Instead of above you can simply use,

isEmpty($data) or 

count($data) or 

$data->count()

Condition Try with this:

if(empty($result->toArray()))
{
    echo "Not Empty check with empty()";
}

if(count($result) == 0)
{
   echo "Not Empty check with count()";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM