0

I am at register.php now. I will be grateful for explanation why !isset() doesn't do the job while empty() perfectly does.

For example,

if (empty($_POST["username"])) {
  apologize("Please, provide your username.");
}

does lead to a message "Sorry! Please, provide your username".

But

if (!isset($_POST["username"])) {
  apologize("Please, provide your username.");
}

leads to a blank page with no messages if I don't enter the username.

I have read the question on Stack Overflow What's the difference between 'isset()' and '!empty()' in PHP? and it seems that both should work fine for the above stated purpose.

2
  • what do you think $_POST["username"] stores when the user submits the form without filling the username field?
    – kzidane
    Jul 28 '16 at 11:49
  • @Kareem: thank you for your answer. Do I assume correctly that $_POST["username"] will store NULL in such case, and thus it will be set, so isset will be true? While empty() checks if the user did type any letters, is it correct?
    – Vitale
    Jul 29 '16 at 16:27
0

If you have a form with a "username" field and user submits it without filling it, an empty string gets sent to the server and therefore $_POST["username"] contains an empty string (""). The empty() function returns true, because the variable is empty, but !isset() returns false, because the variable is set.

See this example:

<?php

$test1 = "test";
$test2 = "";

var_dump(isset($test1)); // true, the variable is set
var_dump(empty($test1)); // false, the variable is not empty because it contains "test"

var_dump(isset($test2)); // true, the variable is set
var_dump(empty($test2)); // true, the variable is empty

var_dump(isset($test3)); // false, the variable is not set
var_dump(empty($test3)); // true, an unset variable is empty

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .