I have a PHP form which allows users to enter up 99 items if they do so desire. I was hoping that PHP doesn't need me to parse each individule item and it can handle doing a loop or something for when there are many items enter.
currently my php looks like this
$item1 = $_POST['Item1'] ;
$item2 = $_POST['Item2'] ;
$item3 = $_POST['Item3'] ;
$item4 = $_POST['Item4'] ;
$item5 = $_POST['开发者_运维知识库Item5'] ;
// etc, etc
But I don't want 99 lines of code if only 5% of people enter more than one item in the form.
Have all the inputs named items[]
(note the []
). You can then access them all in an array called $_POST['items']
. You can then iterate through all the values:
foreach($_POST['items'] as $item)
{
// ...
}
change the input-names like this:
<input type="text" name="items[]"/>
<input type="text" name="items[]"/>
<input type="text" name="items[]"/>
and you'll get an array:
$items = $_POST['items'] ;
foreach($items as $item){
// walk throug items and do something
}
You need to name your input elements like this:
<input type="text" name="Item[]" value="A" />
<input type="text" name="Item[]" value="B" />
<input type="text" name="Item[]" value="C" />
And then in PHP you will see this in $_POST
as an
array(
0 => 'A',
1 => 'B',
2 => 'C'
)
This is a standard PHP trick, and you can use it to get any elements automatically inside the same array when reading them from $_POST
and $_GET
.
Another alternative :
foreach($_POST as $index => $value) {
$item[$index] = $value;
}
for ($i = 1;$i<100;$i++)
{
${"item".$i} = $_POST['Item'.$i];
}
//or you can use variables directly
//echo ($_POST['Item1']);
or you can change Item1, Item2, .... in form to Items[]
and then call it like
$items = $_POST['Items'];
print_r($items);
/*
array
(
[0] => "some"
[1] => "text"
[2] => "another"
[3] => "text"
)
*/
foreach ($_POST as $key=>$value) {
if (substr($key, 0, 4)=="Item") {
$item[substr($key, 4)]=$value;
}
}
精彩评论