开发者

Getting data from $_POST within a for loop

If I have some hidden inputs in my form:

&l开发者_StackOverflowt;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


Inside string literals, variables are only interpolated if the string literal is enclosed in double quotes:

for ($i = 0; $i < 5; $i++) {
  $x = "entry{$i}";
  echo $_POST[$x];
}

For additional safety, you may want to check whether array_key_exists($x, $_POST) before subscripting $_POST, otherwise you would get an error of level E_NOTICE if the passed fields do not correspond.


Try to use array notation:

<input type="hidden" name="entry[0]" value="moredata">
<input type="hidden" name="entry[1]" value="moredata">
<input type="hidden" name="entry[2]" value="moredata">
<input type="hidden" name="entry[3]" value="moredata">
<input type="hidden" name="entry[4]" value="moredata">

<?php
echo implode($_POST['entry']);

for ($i = 0; $i < 5; $i++) {
    echo $_POST['entry'][$i];
}


It is $_POST and not $POST


Firstly check:

echo $POST[$x]; // This does not work.

should be

echo $_POST[$x]; // Note the underscore.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜