WIll there be any reason why if ($str == "") and if (empty($str)) don’t produce the same output?
WIll there be any reason why if ($str == ) and if (empty($str)) don’t
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
$str == ""will return TRUE for$str = "";$str = false;$str = NULL;$str = 0;$str = 0.0;$str == ""will return FALSE for$str = "0";$str = array();Note: It will also return TRUE for an undefined variable but it is a warning.
On the other hand
empty($str)will be TRUE for all the cases above (including the undefined variable), with no warning.As for the reason of this difference, it is because the function
emptyis intended to test for an emtpy variable (of any type, for example an array or a number*) not only an empty string.*: as you may now PHP is happy with numbers stored in strings, it will just convert the value as needed, for example
echo "1" + 2gives3. And that’s whyempty($str)returns TRUE when$str = "0", not because of it being an empty string (it’s not) but because it is an empty number.For testing if an string is empty, I strongly recomend to use either
$str === ''orstrlen($str) === 0.