Is There A Difference Between strlen()==0 and empty()?

匿名 (未验证) 提交于 2019-12-03 08:44:33

问题:

I was looking at some form validation code someone else had written and I saw this:

strlen() == 0

When testing to see if a form variable is empty I use the empty() function. Is one way better than the other? Are they functionally equivalent?

回答1:

strlen is to get the number of characters in a string while empty is used to test if a variable is empty

Meaning of empty:

empty("") //is empty for string empty(0) // is empty for numeric types empty(null) //is empty  empty(false) //is empty for boolean


回答2:

There are a couple cases where they will have different behaviour:

empty('0'); // returns true,  strlen('0'); // returns 1.  empty(array()); // returns true, strlen(array()); // returns null with a Warning in PHP>=5.3 OR 5 with a Notice in PHP<5.3.  empty(0); // returns true, strlen(0); // returns 1.


回答3:

The following things 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) var $var; (a variable declared, but without a value in a class)

strlen() simply check if the the string len is 0. It does not check for int, float etc. What is your situation.

reference



回答4:

$f = 0; echo empty($f)? 'Empty':'Full'; // empty $f = 0; echo strlen($f); // 1

For forms I use isset. It's more explicit. ;-)



回答5:

empty() will return true if $x = "0". So there is a difference.

http://docs.php.net/manual/en/types.comparisons.php



回答6:

empty is the opposite of boolean false.

empty is a language construct.

strlen is a function.

strlen returns the length of bytes of a string.

strlen($str)==0 is a comparison of the byte-length being 0 (loose comparison).

That comparison will result to true in case the string is empty - as would the expression of empty($str) do in case of an empty (zero-length) string, too.

However for everything else:

empty is the opposite of boolean false.

strlen returns the length of bytes of a string.

They don't share much with each other.



回答7:

empty() is for all variables types. strlen(), I think, is better to use with strings or something that can be safely casted to strings. For examle,

strlen(array());

will throw PHP Warning: strlen() expects parameter 1 to be string, array given error



回答8:

when the input is 0,

strlen(0) = 1 empty(0) = false <-- non-empty


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!