Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialgeoffrey
28,736 Pointschecking $_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 ??
<?php
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
austenpayan
10,218 PointsThe 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
Shawn Gregory
Courses Plus Student 40,672 PointsHello,
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.
Cheers!
geoffrey
28,736 PointsThank you for your comments, I'll probably use empty() so.