在 for 循环中从 $_POST 获取数据
如果我的表单中有一些隐藏的输入:
<input type="hidden" name="test" value="somedata">
<input type="hidden" name="entry0" value="moredata">
<input type="hidden" name="entry1" value="moredata">
<input type="hidden" name="entry2" value="moredata">
<input type="hidden" name="entry3" value="moredata">
<input type="hidden" name="entry4" value="moredata">
现在,一旦提交表单并且我从帖子中获取数据,如果我尝试调用 $_POST['test']
然后我会得到我的“somedata”值回来了。但如果我这样做:
for($i = 0; $i < 5; $i++)
{
$x = 'entry{$i}';
echo $_POST[$x]; // This does not work.
}
那么我不会为每个“条目”输入返回“moredata”值。如果我打印出定义为 $x
的字符串,那么我会得到我想要的字符串,但它似乎不想像这样与 $_POST
一起工作。有人知道我如何解决这个问题吗?
谢谢
If I have some hidden inputs in my form:
<input type="hidden" name="test" value="somedata">
<input type="hidden" name="entry0" value="moredata">
<input type="hidden" name="entry1" value="moredata">
<input type="hidden" name="entry2" value="moredata">
<input type="hidden" name="entry3" value="moredata">
<input type="hidden" name="entry4" value="moredata">
Now, once the form is submitted and I'm getting the data from the post, if I try and call $_POST['test']
then I get my "somedata" value back. But if I do this:
for($i = 0; $i < 5; $i++)
{
$x = 'entry{$i}';
echo $_POST[$x]; // This does not work.
}
Then I do not get my "moredata" values back for each 'entry' input. If I print out the string defined as $x
, then I get the string I'm after but it doesn't seem to want to work like this with $_POST
. Anyone got any ideas how I can get around this?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在字符串文字内部,仅当字符串文字用双引号括起来时才会对变量进行插值:
为了提高安全性,您可能需要在下标
$_POST 之前检查
,否则如果传递的字段不对应,您将收到array_key_exists($x, $_POST)
是否存在E_NOTICE
级别的错误。Inside string literals, variables are only interpolated if the string literal is enclosed in double quotes:
For additional safety, you may want to check whether
array_key_exists($x, $_POST)
before subscripting$_POST
, otherwise you would get an error of levelE_NOTICE
if the passed fields do not correspond.尝试使用数组表示法:
Try to use array notation:
它是
$_POST
而不是$POST
It is
$_POST
and not$POST
首先检查:
echo $POST[$x]; // 这不起作用。
应该是
echo $_POST[$x]; // 注意下划线。
Firstly check:
echo $POST[$x]; // This does not work.
should be
echo $_POST[$x]; // Note the underscore.