PHP isset() vs !empty()

11,547

Solution 1

That's because the 'fname' variable is sent anyway, it's just empty but sent!

Try changing your form method from POST to GET and you'll see by yourself.

Solution 2

isset() just checks whether the variable is NULL or not and won't throw an E_NOTICE error if you accessed an undefined index in an array (unlike is_null()).

It does not check whether the variable is containing an empty string!

Solution 3

This seems completely expected to me.

You submitted a form with an element called fname, so even though it was empty it was still set.

Meaning isset evaluates to true, hence you output nothing if you submit with nothing

Solution 4

What is your question?

Using isset() on $_POST['key'] will return true in this circumstance, because the variable itself has been set and passed through from the form. Because you're assigning the value of $_POST['fname'] to the $fname variable, the value will always been assigned, even if it's empty.

empty() will return false if there is no assignment to that variable.

Solution 5

It seems right to me. It happens that when input field is sent empty, it'll be empty in $_POST array, not NULL.

$_POST['fname'] = "";
isset($_POST['fname']) == true;

$_POST['fname'] = "";
!empty($_POST['fname']) == false;

What you could do is use array_key_exists to check it is in $_POST array instead of isset:

$_POST['fname'] = "";
array_key_exists('fname', $_POST) == true; // independent of its value
Share:
11,547
Tural Ali
Author by

Tural Ali

I'm a software architect with 10+ year of experience in various fields.

Updated on June 13, 2022

Comments

  • Tural Ali
    Tural Ali about 2 years

    The problem is when I use

    $fname = isset($_POST['fname']) ? $_POST['fname'] : 'sample';
    die($fname);
    

    in PHP side after form submission with filled fname field getting output exactly what I filled, after submission with unfilled fname input field, getting output ABSOLUTELY NOTHING. Used code !empty instead

    $fname = !empty($_POST['fname']) ? $_POST['fname'] : 'sample';
    die($fname);
    

    after submission with unfilled fname input field, getting output sample.

  • Michael Krelin - hacker
    Michael Krelin - hacker over 12 years
    One might expect is_null() to check if it's null or not and isset() to check whether it is set at all. Sadly, though, your description is accurate.