Skip to content
This repository has been archived by the owner on Sep 9, 2019. It is now read-only.

Enhancement: StringHelper::isEmpty() #166

Closed
np25071984 opened this issue Feb 12, 2019 · 7 comments
Closed

Enhancement: StringHelper::isEmpty() #166

np25071984 opened this issue Feb 12, 2019 · 7 comments

Comments

@np25071984
Copy link
Contributor

From documentation

The following values are considered to be empty:

"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)

In case of "0" input value, the result isn't obvious. For me it is a string as is and the construction have to return FALSE!

So, my offer is to rely on string length instead of empty() function:

public static function isEmpty($s, $trim = true)
{
    $s = (string) $s;
    if ($trim) {
        $s = \trim($s);
    }
    return strlen($s) === 0;
}
Q A
Yii version 2.0.?
PHP version
Operating system
@samdark
Copy link
Member

samdark commented Feb 13, 2019

That's simple enough check not to have a special wrapper for it:

if (\trim($string) === '') {

@samdark samdark closed this as completed Feb 13, 2019
@np25071984
Copy link
Contributor Author

That's simple enough check not to have a special wrapper for it:

if (\trim($string) === '') {

What about null? What about type casting (int, obj)? I use such function all the time and think it is quite useful.

@np25071984
Copy link
Contributor Author

Wow...
It may be useful to know that trim() returns an empty string when the argument is an unset/null variable.
I didn't know that! You are right, isEmpty now useless.

@np25071984
Copy link
Contributor Author

And one more question - I used to use helper ArrayHelper::isSet($array, $path) which takes an array and a key path and check if the path exists.

isSet([
  [
    'one' => 'One',
    'two' => [
        'label' => 'Two',
        'value' => 2
    ],
  ],
], 
'0.two.label') // true

Can I do the same by native php function?

@samdark
Copy link
Member

samdark commented Feb 14, 2019

No, that you cannot do with native function.

@mozarcik
Copy link

Actually he can do this

isset($arr[0]['two']['label'])

It checks for all keys and when any defined does not exist it returns false, I don't see a reason to use dot syntax here

@tomaszkane
Copy link

BTW, I like null operator on similar case:
return $array['foo']['boo'] ?? false;

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants