1

Why can't I use empty ($example->body), and need to use $example->body->isEmpty() to check for empty array. What is the return type that causes it can't use empty() and need to rely on isEmpty()?

I do know this is from Laravel Collection based on this post. But didn't really understand why behind the scene. Any enlighten is greatly appreciated (but I'll try to understand it from freshgrad POV)

Community
  • 1
  • 1
John
  • 348
  • 5
  • 10

2 Answers2

1

empty() cannot work because it always returns true

Because if you dd($example); you'll notice you'll notice an instance of Illuminate\Support\Collection is always returned, even when there are no results. Essentially what you're checking is $a = new stdClass; if ($a) { ... } which will always return true.

Source

Community
  • 1
  • 1
EddyTheDove
  • 12,979
  • 2
  • 37
  • 45
1

PHP empty manual.

Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE.

In the manual they provided things that are considered to be empty. object type is not part of it. Instance of Laravel collection (Illuminate\Support\Collection) is considered as a object type. It doesn't matter if the object is plain empty object for PHP, the empty() will always returns false

Saumini Navaratnam
  • 8,439
  • 3
  • 42
  • 70
  • Thank you. I understand the PHP empty() return TRUE or FALSE flag depends on the empty. But I didn't grasp on why it's consider empty() FALSE. If it's consider as object, then it'll always return FALSE via empty(). – John Feb 08 '17 at 05:43