View Full Version : incrementing a variable

03-17-2010, 11:38 PM
I don't know what this is called in order to referece it. Basically I see that you can do a loop to automatically increment a variable (not the value of a variable) like this:

$var1 = "line 1<br>";
$var2 = "line 2<br>";
for ( $i = 1; $i <= 40; $i++) {
echo ${'var'.$i};

What I don't know if it's possible is to do that with a $_POST. For example after a person submits a form with 40 fields, it sends to $_POST['field1'] and so on to 40. Instead of echoing every $_POST or manually assigning it an intermediate variable, I'd just like to do an incremental loop with the $_POSTs for the handling.

1. What is the ${'var'.$i} concept called?
2. How would this work with $_POST?

03-17-2010, 11:42 PM
with regards to curly bracers and echoing ~ http://www.nusphere.com/kb/phpmanual/language.types.string.htm#language.types.string.parsing.complex

with regards to post and lots of fields ~ http://php.net/manual/en/control-structures.foreach.php

03-17-2010, 11:44 PM
Use an array; that will let you control the size of the variables:

<input type="text" name="field[1]" />
<input type="text" name="field[2]" />

foreach ($_POST['field'] AS $key => $value)
printf("Field offset: %d = %s\n", $key, $value);

// Or:
$iFieldCount = count($_POST['field']);
for ($i = 0; $i < $iFieldCount; ++$i)
printf("Field offset: %d = %s\n", $i, $_POST['field'][$i]);

In response to you're first question, thats called concatination of strings to be interpreted later as a variable. This is IMO a bad approach. Arrays are much more simplistic and easy to go. $_POST itself can be completely iterated and evaluated on an individual level for each key / value combinations. Above code shows if you were to group a particular part as an array, which would make sense for things like radio buttons, potentially password verifications, user bio information, and whatnots.