0

I am having a form with name, radios and email.

<form action="index.php" method="POST" role="form">
    <input class="form-control" name="name" type="text" placeholder="NAME">
    <input class="form-control" name="email" type="text" placeholder="EMAIL(optional)">

    <input type="radio" class="form-check-input" name="gender" value="male">Male
    <input type="radio" class="form-check-input" name="gender" value="female">Female
    <input type="radio" class="form-check-input" name="gender" value="other">Other
    ...

To test whether name, email or radios are filled in, i use isset

if (isset($_POST['name'])) {
    echo 'name isset';
}
    if (isset($_POST['email'])) {
    echo 'email isset';
}
if (isset($_POST['gender'])) {
    echo 'gender isset';
}

What i don't understand: even when i leave the fields empty, it outputs the 2 echo's from the name and email loop, but NOT the gender loop.

Can someone explain me why the return values of name and email are TRUE even when i leave the fields empty and submit? And why, if i do not click any of the radios, this return value is FALSE? ( echo 'gender isset'; is not outputted!)

Jonas
  • 121,568
  • 97
  • 310
  • 388
john
  • 1,263
  • 5
  • 18

1 Answers1

2

Because if you leave the fields empty, they send an empty string to the server. Meaning the $_POST['name'] will contain empty string ''

Function isset checks if the value exists and is different from null. In your case empty string is different from null and exists.

You can use empty instead and it will work.

For example:

if (!empty($_POST['name'])) {
    echo 'name isset';
}

As for the radios - they are not sent, if none are selected. That's why isset works there.

vuryss
  • 1,270
  • 8
  • 16
  • Thanks for comment. I made a mistake by thinking that `''` is the same as `NULL`. Now i understand the issue! – john Mar 02 '20 at 21:51