Jump to content

Where to and why to use empty()


bunder5
 Share

Recommended Posts

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?

 

 

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.