Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.


28,724 Points

checking $_POST["data"] with empty()

I'd like to know, isn't it better to use the empty function instead of comparing our variable with an empty string ??


if(empty($name) || empty($email) || empty($message)){


// instead of just

if ($name =="" || $email=="" || $message==""){


I've heard that was better, but I don't know the exact reason...

3 Answers

The empty() function checks more than just an empty string, it also checks integers, floats, arrays, undefined variables, and more. So yes you heard right, it is better, simply for the reason that it checks more than just strings for emptiness.

read about it here: http://us2.php.net/empty


You would use empty when you are not sure if the variable you are checking even exists. If you use the empty function on a variable that doesn't exist, you will get false as expected; however, if you use $var == "" and $var doesn't exist, you will get a warning from the PHP parser as the variable $var doesn't exist. I prefer to use empty over checking to see if a variable is empty but that's just my preference. Both are useable but in my opinion, since (by the looks of the name of the post) you are checking user input, I would use the empty in case the array variable doesn't exist.


28,724 Points

Thank you for your comments, I'll probably use empty() so.