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

那年仲夏 提交于 2019-12-05 05:08:04

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
Paul

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.

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

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

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

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

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

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.

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

when the input is 0,

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