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

霸气de小男生 提交于 2019-12-10 09:57:08

问题


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.


回答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.




回答2:


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




回答3:


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> 



回答4:


The major difference is isset determine variable is set and is not null for $_POST is not work here because you are not define here input name. The $_POST consider an array of inputs name/values pairs.



来源:https://stackoverflow.com/questions/34609086/php-if-post-vs-ifisset-post

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!