How to define an array of form fields PHP

2019-09-03 23:20发布

问题:

I have a question.

I have this code in the first page:

<input type="text" name="number" id="number">
<input type="submit" name="button_add" id="button_add" value="add">
<? 
$i=0;
while($number>$i) { $i++; ?>
  <div align="left">
  <input type="text" name="text[<? echo $i; ?>]" id="text[<? echo $i; ?>]" /><? } 
?>

How do I define the array of fileds in the next page using $_POST vars?

回答1:

The entry in $_POST is itself an array, if that's what you're asking:

for ($i = 0; $i < count($_POST['text']); ++$i) {
    // do something with this post:
    $_POST['text'][$i];
}

or:

foreach ($_POST['text'] as $i => $text) {
    // do something with:
    $text;
    // Note: $text === $_POST['text'][$i]
}

Off-topic

Always close your elements:

<input type="text" name="number" id="number" />
<input type="submit" name="button_add" id="button_add" value="add" />

You also neglected to close the <div> wrapping the text[] inputs. If you don't, your document is ill-formed and, though browsers will attempt to parse the document, there's no guarantee they'll do it the way you want.

The default type for inputs is text. It doesn't hurt to set the type attribute to "text", but it isn't necessary.

Don't rely on short tags; use the full <?php. Not all hosts will have them enabled, and they're deprecated and will be going away soon (there's been some talk about doing away with them before PHP 5).

You don't need to explicitly assign array indices for your input names; empty brackets will cause the value to be assigned to the end of the array. Also, '[' and ']' aren't valid characters for IDs.

<input type="text" name="text[]" id="text_<?php echo $i; ?>" />

A for loop is more appropriate than a while loop in your code. Though both do the same thing, they have different connotations (a while loop repeats while some static condition holds under changing circumstances; a for loop repeats over a sequence).

for ($i=0; $i < $number; ++$i) {

All together, we have:

<input name="number" id="number" />
<input type="submit" name="button_add" id="button_add" value="add" />
<?php for ($i=0; $i < $number; ++$i): ?>
  <div align="left">
    <input name="text[]" id="text_<?php echo $i; ?>" />
  </div>
<?php endfor; ?>


回答2:

Try:

foreach( $_POST['text'] as $key => $value){
 echo "Value for texbox # ".$key." is:". $value;
    // or whatever code you want
}

In the page the form submits to.



回答3:

I'm on a netbook and it would be apain to write the code let alone test it.

use a loop and the post var and isset function.