Skip to content

Empty Checking

Sugar uses EmptyHelper::isEmpty() for s:empty and s:forelse instead of PHP's empty(). This provides consistent behavior across arrays, countable objects, and iterators while avoiding false positives.

INFO

empty() treats some values (like 0 and "0") as empty. EmptyHelper follows those rules for scalars, but adds smarter handling for objects and iterables.

What Counts As Empty

  • null, false, '', '0', 0, 0.0
  • Arrays with zero items
  • Countable objects with a count of zero
  • Traversable iterators with no items

Everything else is considered non-empty.

Examples

php
EmptyHelper::isEmpty(null);   // true
EmptyHelper::isEmpty('0');    // true
EmptyHelper::isEmpty(0);      // true
EmptyHelper::isEmpty('ok');   // false
php
EmptyHelper::isEmpty([]);          // true
EmptyHelper::isEmpty(['x']);       // false
php
EmptyHelper::isEmpty(new ArrayObject([])); // true
php
$iter = new ArrayIterator([]);
EmptyHelper::isEmpty($iter); // true

Generators

Generators cannot be checked without consuming them. EmptyHelper throws a GeneratorNotSupportedException if you pass a generator.

php
$generator = (function () {
    yield 1;
})();

EmptyHelper::isEmpty($generator); // throws GeneratorNotSupportedException

TIP

Convert generators to arrays before using them with s:empty or s:forelse.

In Templates

html
<ul s:forelse="$items as $item">
    <li><?= $item ?></li>
</ul>
<div s:empty>No items found</div>