PHP-正确检查$ _POST ['variable']是否发布 [英] PHP - proper check if $_POST['variable'] is posted
问题描述
我要检查是否发布了$ _POST ['submit'].
I want to check if $_POST['submit'] is posted.
我的原始代码是:
if ($_POST['submit']) { }
但是我有一个PHP通知,其中包含以下代码-未定义的索引:在...中提交"
But I have a PHP notice with this code - "Undefined index: submit in..."
所以要删除通知,我必须这样写:
So to remove the notice I have to write this:
if (isset($_POST['submit'])) { }
但这是没有意义的,因为$ _POST数组是全局数组,并且它始终返回true. 另外,如果我想在没有PHP通知的情况下检查$ _POST ['submit']是否不为0,我必须这样写:
But this is pointless because $_POST array is global and it return always true. Also if I want to check if $_POST['submit'] is not 0 without PHP notice I have to write this:
if (isset($_POST['submit']) && $_POST['submit'] != 0) { }
在这种情况下,我更喜欢:
In this particular case I prefer:
if ($_POST['submit']) {}
但是在这里,我得到了PHP通知.
But here I get the PHP notice.
那哪种方法最合适/可以接受?
So which way is the most proper/accepted?
谢谢
推荐答案
isset($_POST['submit'])
检查是否在$_POST
数组中设置了submit
键.它不仅检查$_POST
数组是否存在,因此不是毫无意义的".如果要检查是否包含0
的 not falsey (== false
)值,而不会触发错误,则empty
就是这样的:
isset($_POST['submit'])
checks if the submit
key is set in the $_POST
array. It doesn't just check whether the $_POST
array exists and is therefore not "pointless". If you want to check whether the value is not falsey (== false
), which includes 0
, without triggering an error, that's what empty
is for:
if (!empty($_POST['submit']))
与
if ($_POST['submit'])
但该值不存在时不触发通知.
but without triggering a notice should the value not exist.
有关详尽的说明,请参见有关PHP的isset和空的权威指南.
See The Definitive Guide To PHP's isset And empty for an exhaustive explanation.
这篇关于PHP-正确检查$ _POST ['variable']是否发布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!