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 trial

PHP

geoffrey
geoffrey
28,736 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 ??

<?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

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

Hello,

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
geoffrey
28,736 Points

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