Question

I found something strange happening with this:

if(isset($_POST['name'])){
    echo $_POST['name'];
}
else{
    echo "please enter name";
}

in the above example the else statement does not work.

if(empty($_POST['name'])){
    echo "please enter name";
}
else{
    echo $_POST['name'];
}

but when I do it like this, it works. Can anybody tell me why this is happening?

Was it helpful?

Solution 2

I'm assuming you are submitting a form, where the field name is empty, but it exists (or in other words isset).

The difference between isset and empty is, that the latter assumes that $_POST['name'] exists, but contains an empty value, e.g. "" or 0, whereas the first only checks if $_POST contains an element name.

When your form contains a field, it will be submitted and therefore is set, whether it has any contents or not (i.e. is empty).

OTHER TIPS

Try this:

isset() function is not able to fetch blank && zero value.

so always use empty() with it.

if(isset($_POST['name']) && !empty($_POST['name']))
{
    echo $_POST['name'];
}
else 
{
    echo "please enter name";
}

-- Thanks

$_POST['name'] is getting set but it contains null value so add if((isset($_POST['name'])) and (empty($_POST['name']))

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top