Core\Str::isEmpty
Checks whether a string is empty, which means it has no characters at all.
Core\Str::isEmpty returns true for the empty string "" and false for every other string. A string that has only spaces is not empty, and neither is "0". If spaces should count as empty, for example in a form field, call Core\Str::trim first and check its result.
The check takes the same short time for a long string and a short one, because it does not count the characters.
Good to know: Core\Str::isEmpty("0") returns false, because "0" has one character.
Parameters
$sstringThe string to check.
Return value
Returns bool. true when $s has no characters, otherwise false.
Examples
Empty or not
<?nvs// Shows which strings `Core\Str::isEmpty` counts as empty.
// Only the first string is empty. A space and "0" are characters too,// so this prints `empty` once and then `not empty` three times.array<string> $values = ['', ' ', '0', 'hello'];foreach ($values as string $value) { if (Core\Str::isEmpty($value)) { echo '[', $value, "] empty\n"; } else { echo '[', $value, "] not empty\n"; }}[] empty[ ] not empty[0] not empty[hello] not emptyA required field
<?nvs// Shows how to check that a required form field was filled in.
class Form{ // `Core\Str::trim` removes the spaces around the value first. // A field with only spaces then counts as empty. public static function check(string $label, string $value): string { if (Core\Str::isEmpty(Core\Str::trim($value))) { return $label . ' is required'; } return $label . ' is OK'; }}
// This prints `Name is OK`, `Email is required` and `City is required`.echo Form::check('Name', 'Anna'), "\n";echo Form::check('Email', ''), "\n";echo Form::check('City', ' '), "\n";Name is OKEmail is requiredCity is requiredSkip blank lines
<?nvs// Shows how to read a list that a user pasted, one entry per line, and skip the blank lines.
string $pasted = "anna@example.com\n\nben@example.com\n \ncarla@example.com\n";
// `Core\Str::lines` splits the text into lines. A line that is empty// after `Core\Str::trim` is skipped. This prints the three addresses and `3 addresses`.uint $count = 0;foreach (Core\Str::lines($pasted) as string $line) { string $address = Core\Str::trim($line); if (Core\Str::isEmpty($address)) { continue; } echo $address, "\n"; $count = $count + 1;}echo $count, " addresses\n";anna@example.comben@example.comcarla@example.com3 addresses