TeddyKiller Posted April 23, 2010 Share Posted April 23, 2010 I probs know the answer to this, I just need reassuring that I've got it right. If I have a variable.. $user = ''; This can be used as.. if(empty($user)) { } Though if that variable isn't defined.. would the same line work? If not.. would doing it as if(!$user) { } work? Quote Link to comment https://forums.phpfreaks.com/topic/199514-empty-variables/ Share on other sites More sharing options...
Ken2k7 Posted April 23, 2010 Share Posted April 23, 2010 Yes, empty will work. The !(boolean) $user would result in true. Basically speaking, empty($var) and (boolean) $var are opposites. Quote Link to comment https://forums.phpfreaks.com/topic/199514-empty-variables/#findComment-1047160 Share on other sites More sharing options...
dirkers Posted April 23, 2010 Share Posted April 23, 2010 empty() will have covered if the variable is an empty string or undefined. Don't use if (!$user) { }. However, be careful with empty() because it also returns TRUE for the integer 0 and string "0". For more details on empty(), take a look at the empty() PHP Manual page. Depending on your scenario, you might want to look at isset(). -D Quote Link to comment https://forums.phpfreaks.com/topic/199514-empty-variables/#findComment-1047176 Share on other sites More sharing options...
Ken2k7 Posted April 23, 2010 Share Posted April 23, 2010 dirkers, could you please explain why we should not use if (!$user) { }? Quote Link to comment https://forums.phpfreaks.com/topic/199514-empty-variables/#findComment-1047178 Share on other sites More sharing options...
TeddyKiller Posted April 23, 2010 Author Share Posted April 23, 2010 if(empty($user)) works fine. Although.. same as what Ken2k7 ^^ Quote Link to comment https://forums.phpfreaks.com/topic/199514-empty-variables/#findComment-1047183 Share on other sites More sharing options...
DavidAM Posted April 23, 2010 Share Posted April 23, 2010 dirkers is correct. The OP was asking about undefined variables. If you use if(!$user) and the variable is not defined, PHP will throw an error. Quote Link to comment https://forums.phpfreaks.com/topic/199514-empty-variables/#findComment-1047221 Share on other sites More sharing options...
Ken2k7 Posted April 23, 2010 Share Posted April 23, 2010 dirkers is correct. The OP was asking about undefined variables. If you use if(!$user) and the variable is not defined, PHP will throw an error. It'll throw a notice, but not really an error. Quote Link to comment https://forums.phpfreaks.com/topic/199514-empty-variables/#findComment-1047251 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.