!empty($myfield) vs. $myfield->isNotEmpty()

Hello. Just a quick question here.


if(!empty($myfield)): // do something endif;

The same as…

if($myfield->isNotEmpty()): // do something endif;

First of all, empty() only works with a variable. Secondly, it will not successfully check if a field is empty or not.

No, the first example won’t work. It will always tell you that the field is not empty even though it is. The reason is that fields are always objects and objects are never empty to PHP.

Thanks for the insight.

I tend to get caught up on how to check if a piece of data exists in order to split it out or not. I understand this may relate more to PHP rather than Kirby. And the item that I’m checking (variable, object, etc.) might require different approaches. I don’t think I really nailed down what needs what approach.

Would it be safe to say I can always use the isNotEmpty to check any piece of data stored in Kirby? I see ->count() being used too. Is there one approach that I can stick with or does it simply depend?

No, ->isNotEmpty() will only work with fields. empty() will work with PHP strings. ->count() will work with collections (pages, files etc.). So it all depends on the return value. Sometimes the return value is false, you can’t use methods on that. But you can use empty(). Yes, complicated, you are right. :slight_smile:

I see. I, for one, would love to have a go-to function that can handle any type of data type (variable, object, etc.) to determine if it’s there to output. Thanks.

I see your point, but different types have different understandings of “something to output”. Learning the API is some work, but I think it is worth it.

I think that’s a topic that’s certainly worth a cookbook recipe. At least then we have everything in one place for reference.