检查长度至少为 1 个字符的字符串
我经常看到 strlen 使用。这两个测试对于 $str
的所有值都等效吗?
is_string($str) && 0 !== strlen($str)
is_string($str) && '' !== $str
I often see strlen used. Are these 2 tests equivalent for all values of $str
?
is_string($str) && 0 !== strlen($str)
is_string($str) && '' !== $str
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,这两种说法在逻辑上是等价的。我最喜欢的给这只猫剥皮的方法:
...虽然
empty('0')
是true
(叹息,PHP...),所以这可能更好:另请参阅:检查字符串是否为空和 $str == '' 和 之间有区别吗PHP 中的 strlen($str) == 0?
Yes, those two statements are logically equivalent. My preferred ways to skin this cat:
...though
empty('0')
istrue
(sigh, PHP...), so this is probably even better:See also: Checking if the string is empty and Is there a difference between $str == '' and strlen($str) == 0 in PHP?
它们非常接近,除了
strlen()
将为NULL
字符串返回0
,因此如果您的$str
> 为NULL
,第一个测试中的0 !== strlen($str)
表达式的计算结果将为true
,而'' !== $str
在你的第二个测试中将评估为假
。They're pretty close, except that
strlen()
will return0
forNULL
strings, so if your$str
wasNULL
, the0 !== strlen($str)
expression in your first test would evaluate totrue
, while the'' !== $str
in your second test would evaluate tofalse
.是的,它们是相同的..
我会使用:
yes, they are the same..
I would use:
试试这个
!== 是强类型,可能无法正确匹配 0。
Try this
!== is a strong type and might not be match the 0 properly.