Enhancement: StringHelper::isEmpty()
np25071984 opened this issue · 7 comments
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 |
That's simple enough check not to have a special wrapper for it:
if (\trim($string) === '') {
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.
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.
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?
No, that you cannot do with native function.
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
BTW, I like null operator on similar case:
return $array['foo']['boo'] ?? false;