bunder5 Posted November 3, 2011 Share Posted November 3, 2011 I don't get the logic behind the construct. I can't ever see myself using this because it doesn't make sense when I code it. I understand isset($var) and why I should use it sometimes to avoid undefined messages. But with empty() it makes more sense to always test the variable directly because if the value is NULL, 0, '', or false then it evaluates as TRUE. Is there any situation where empty should be used always? Quote Link to comment https://forums.phpfreaks.com/topic/250345-where-to-and-why-to-use-empty/ Share on other sites More sharing options...
phporcaffeine Posted November 3, 2011 Share Posted November 3, 2011 I don't get the logic behind the construct. I can't ever see myself using this because it doesn't make sense when I code it. I understand isset($var) and why I should use it sometimes to avoid undefined messages. But with empty() it makes more sense to always test the variable directly because if the value is NULL, 0, '', or false then it evaluates as TRUE. Is there any situation where empty should be used always? empty() is an attempt to simplify things. The function itself, checks for the empty or zero value of string, int and array types. It will return true for everything empty or of zero value, false for anything else. Using empty is great because the name is intuitive when your reading large amounts of code and it's pretty universal in terms of the data types it works with. I've never had issues with it. That said, empty() is the sort of function that loves to get deprecated by language maintainers (not that I have gotten that impression from PHP). Using empty sort of puts all your eggs in one basket; if something happens to empty(), it affects a lot of code. Conversely, if you practice implicit comparisons $a === 0, $a == "" ... etc, then you'll never be affected by baked-in function deprecation. Its tomato tamato; one of the things PHP is famous for is having 18 ways to do a single task, its also a big detractor Some Examples: $a = array() count($a) //would return 0 empty($a) //would return true $a = 0 $b = "0" empty($a) //would return true empty($b) //would return true Here is the PHP manual entry for empty(): http://us3.php.net/empty Quote Link to comment https://forums.phpfreaks.com/topic/250345-where-to-and-why-to-use-empty/#findComment-1284586 Share on other sites More sharing options...
bunder5 Posted November 3, 2011 Author Share Posted November 3, 2011 Thanks, I understand it better now. Quote Link to comment https://forums.phpfreaks.com/topic/250345-where-to-and-why-to-use-empty/#findComment-1284743 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.