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

27,741

Solution 1

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.

Solution 2

It is because the $_POST is an array of inputs names/values pairs, and in your form no input has any name, therefore it is an empty array (evaluating to false). You can verify it by var_dump($_POST).

Try to add a name to text input to access its value:

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

Solution 3

isset determines if a variable is set and not NULL, see the manual: http://php.net/manual/en/function.isset.php

while if($_POST) checks $_POST for being true.

in your case, $_POST will always be set. If doing that with other variables not related to a form, keep in mind that checking for if($var) without knowing if it is set or not, will throw a notice. Checking if(isset($var)) will not throw a notice.

Unrelated to your question: if you want to know if there is data inside your $_POST array you could try working with count($_POST), see: http://php.net/manual/en/function.count.php

Share:
27,741
Aycan Yaşıt
Author by

Aycan Yaşıt

I am a professional software developer who prefers PHP, but is mostly forced to use .NET unevitably.

Updated on July 24, 2022

Comments

  • Aycan Yaşıt
    Aycan Yaşıt almost 2 years

    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.

  • maxhb
    maxhb over 8 years
    For comparisons php will convert (type cast) the ´$_POST` array to a boolean value of true or false. If an array is empty it will be converted to false and to true otherwise.