Forum Moderators: coopster

Message Too Old, No Replies

using!isset() and empty() to check for required form field

         

tyrone04

10:43 pm on Aug 19, 2005 (gmt 0)

10+ Year Member



Forgive my naive question, i'm an inexperienced php'er who only knows a bit of this and a bit of that.....

I was reading the "Basics of Submitting and Emailing Forms with PHP" post by jatar_k in the Library and came across how both!isset() and empty() are used to check against a required form input field.

if (!isset($_POST['firstname']) ¦¦ empty($_POST['firstname'])) $errmsg .= "<p>Please enter your first name";

According to jatar_K, the line checks to see if the variable is set and has a value in it.

My question is: doesn't!isset() alone do the job already? why use empty() also? According to php.net, isset() checks to see if a variable is set (if the variable exits and has a value in it).

empty() is used also is it because isset() returns TRUE even if the variable has an empty value? So using empty() adds another layer of error checking to it.

Thanks!

jatar_k

10:56 pm on Aug 19, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Welcome to WebmasterWorld tyrone04,

try this little test

<?
if (isset($var1)) echo '<p>var1 isset';
else echo '<p>var1 is not set';
if (empty($var1)) echo '<br>var1 is empty';
else echo '<br>var1 is not empty';

$var2 = '';
if (isset($var2)) echo '<p>var2 isset';
else echo '<p>var2 is not set';
if (empty($var2)) echo '<br>var2 is empty';
else echo '<br>var2 is not empty';

$var3 = 'something';
if (isset($var3)) echo '<p>var3 isset';
else echo '<p>var3 is not set';
if (empty($var3)) echo '<br>var3 is empty';
else echo '<br>var3 is not empty';
?>

I had problems with a few vars a couple times with weird results and used the line you quoted to correct it. I have never switched away from it though often I add a third piece to the if statement to check it is also of the proper type.