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?
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?
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 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.
$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.
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