Victor
Victor

Reputation: 99

How to define an array of form fields PHP

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?

Upvotes: 0

Views: 2989

Answers (3)

outis
outis

Reputation: 77400

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; ?>

Upvotes: 4

Yehonatan
Yehonatan

Reputation: 1172

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.

Upvotes: -2

SW4
SW4

Reputation: 71150

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.

Upvotes: 3

Related Questions