Page 1 of 1

Variable with variable name in it

Posted: Sat Oct 18, 2003 4:00 pm
by bomax
Hello!

I have a form which generates a user-definable number of input boxes (lets set the number of boxes in $x). I then named each text box like this "option$x" so the output is option1, option2, option3, etc.

Now of course on the next page I will want to process and store the values entered in the text boxes. This is where the problem arises. Is there a way I can use a loop to gather the values of each box? I tried using $option$x but it didn't work. I'm sure some of you have run in to this problem in the past.

Any help is much appreciated!

Posted: Sat Oct 18, 2003 4:13 pm
by Gen-ik
Try this.....

Code: Select all

$boxValue = ${"option".$x};

Posted: Sat Oct 18, 2003 4:24 pm
by volka
php knows variable variables but you do not need them for this
Since you should use the superglobals $_POST and $_GET to retrieve user input (see also: http://forums.devnetwork.net/viewtopic.php?t=511) all you need to do is to create appropriate indices for the array, e.g.

Code: Select all

<html>
	<head>
		<title>variable elements test</title>
	</head>
	<body>
<?php if (isset($_POST['text0'])) { ?>
		<fieldset><legend>previous input</legend>
<?php
	for($i=0; isset($_POST['text'.$i]) && strlen($_POST['text'.$i])>0; $i++)
		echo "text$i is: ", htmlentities($_POST['text'.$i]), '<br />';
?>
		</fieldset>
<?php } ?>	
		<form method="POST" action="<?php echo $_SERVER['PHP_SELF'];?>">
			<input type="text" name="text0" /><br />
			<input type="text" name="text1" /><br />
			<input type="text" name="text2" /><br />
			<input type="text" name="text3" /><br />
			<input type="submit" />
		</form>
	</body>
</html>
it might be simpler to use arrays

Code: Select all

<html>
	<head>
		<title>variable elements test</title>
	</head>
	<body>
<?php if (isset($_POST['texts']) && is_array($_POST['texts'])) { ?>
		<fieldset><legend>previous input</legend>
<?php
	foreach($_POST['texts'] as $index=>$text)
		echo $index, '=>', htmlentities($text), '<br />';
?>
		</fieldset>
<?php } ?>	
		<form method="POST" action="<?php echo $_SERVER['PHP_SELF'];?>">
			<input type="text" name="texts[]" /><br />
			<input type="text" name="texts[]" /><br />
			<input type="text" name="texts[]" /><br />
			<input type="text" name="texts[]" /><br />
			<input type="submit" />
		</form>
	</body>
</html>
(note the [] in name="texts[]")
If your version of php is not recent enough to support $_POST, ... try $HTTP_POST_VARS, ... (and consider an upgrade if possible)

Posted: Sun Oct 19, 2003 12:08 pm
by bomax
Thank you both for the excellent replies! :worship: :)