Php if($_POST) vs if(isset($_POST))

Aycan Yaşıt picture Aycan Yaşıt · Jan 5, 2016 · Viewed 24.2k times · Source

I have a simple form as demonstrated below:

<form action="" method="post">
  <input type="text" />
  <input type="submit" value="SEND" />
</form>

When I try to receive data sent from this form via if($_POST), I fail, but when try with isset, I success.

if($_POST){
  echo 'a'; //Doesn't print anything.
}
if(isset($_POST)){
  echo 'b'; //Prints 'b'
}

I guess the reason behind it is missing name attribute in my form input, but I can't understand why if($_POST) and isset($_POST) react different ways in this case.

Answer

Quentin picture Quentin · Jan 5, 2016

isset determine if a variable is set and is not NULL. $_POST will always be set and will always be an array.

Without isset you are just testing if the value is truthy. An empty array (which $_POST will be if you aren't posting any data) will not be truthy.