Log in

View Full Version : Dynamic variable naming?



Irishjugg
12-08-2008, 02:47 AM
Hey all,
sort of new to php, but I am a c++ etc coder so I know general coding practice.

If there a way for me to have a dynamic number of text inputs on a php page in a form, which I am naming foo$ct where $ct is postincremented in my while loop. Can I on the action= page load those variables as $foo$c where $c is a for loop on 0 -> $ct?

Or should I just be storing everything with an array?

Some code:

while($row = mysql_fetch_array($result)) {
?>
<tr>
<td>
<?php
$sht = trim($row['shortannounce']);
print "<input type=\"hidden\" name=\"key$ct\" value=\"$sht\" />";
print "<textarea rows=\"4\" cols=\"40\" class=\"small\" name=\"stannounce$ct\">".$sht;
?>
theres a $ct++; at the end of the while loop.

How should I better handle this issue of dynamicly named inputs for the action page?

Irishjugg
12-08-2008, 03:38 AM
Ive been looking around the interwebs, this problem is basically the what do I do after I make a dynamic form. I have all the different inputs to handle, how do I dynamically handle them?

Irishjugg
12-08-2008, 05:15 AM
Nevermind, I found a solution.

Thanks to anyone who read.

Twey
12-08-2008, 10:56 AM
The correct method is to make the inputs into an array, by giving them the same name which should end with a []. If you ever find yourself using anything resembling variable variables, you're Doing It Wrong®.

Irishjugg
12-10-2008, 05:57 PM
I just ended up making a variable name as a string as $inputtemp = "thing$i" then loading $inputtemp or something like that.

I guess its ALMOST like a variable variable, but not quite as I have no $$'s, for example:
$st = trim($_POST['stannounce'.$i]);

With the way using your array Im still a bit confused, but the solution I have works, is what Im doing bad coding practice?

Twey
12-10-2008, 07:36 PM
Yes. It's unnecessary here, and vastly overcomplicated. Input arrays are the way to go for variable numbers of inputs.