iterating form variables in php

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
tembss
Forum Newbie
Posts: 2
Joined: Tue May 13, 2003 7:33 am
Location: RSA

iterating form variables in php

Post by tembss »

I need an example of code that iterates variables in a form in php - something equivalent to the "Request.Form.count" or "Request.Form.Key(i)" in ASP.
User avatar
patrikG
DevNet Master
Posts: 4235
Joined: Thu Aug 15, 2002 5:53 am
Location: Sussex, UK

Post by patrikG »

Not sure if I understand your problem exactly...

PHP receives form variables as an array: either $_POST["variablename"] or $_GET["variablename"].

Say you have submitted a form to a page with the code:

Code: Select all

<?php
if($_POST)
  {
  foreach($_POST as $key=>$value)
     printf "$key: $value";
  }
?>
Also, extract may come in handy.

If you are referring to the form-objects - use javascript and loop through the form-element.

Any closer to the solution?
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

try

Code: Select all

<html>
	<head><title>request iteration example</title></head>
	<body>
		<fieldset><legend>$_REQUEST</legend>
			<pre><?php print_r($_REQUEST); ?></pre>
		</fieldset>
		<fieldset><legend>$_POST</legend>
			<pre>
<?php
foreach($_POST as $key=>$value)
	echo $key, '=>', $value, "\n";
?>
			</pre>
		</fieldset>
		<fieldset><legend>$_GET</legend>
			<pre>
<?php
foreach($_GET as $key=>$value)
	echo $key, '=>', $value, "\n";
?>			
			</pre>
		</fieldset>
<?php	echo 'parameter <i>p1</i> has ', isset($_POST['p1']) ? 'been sent' : 'not been sent'; ?>
		<hr />
		<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" style="background-color: silver;">
			<label for="p1">checkbox #1</label><input type="checkbox" id="p1" name="p1" /><br />
			<label for="p2">checkbox #2</label><input type="checkbox" id="p2" name="p2" /><br />
			<label for="p3">checkbox #3</label><input type="checkbox" id="p3" name="p3" /><br />
			<label for="p4">checkbox #4</label><input type="checkbox" id="p4" name="p4" /><br />
			<input type="submit" />
		</form>
		<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="GET" style="background-color: grey;">
			<label for="g1">checkbox #1</label><input type="checkbox" id="g1" name="g1" /><br />
			<label for="g2">checkbox #2</label><input type="checkbox" id="g2" name="g2" /><br />
			<label for="g3">checkbox #3</label><input type="checkbox" id="g3" name="g3" /><br />
			<label for="g4">checkbox #4</label><input type="checkbox" id="g4" name="g4" /><br />
			<input type="submit" />
		</form>
	</body>
</html>
and read http://www.php.net/manual/en/reserved.variables.php , http://php.net/foreach

edit: oops, again too slow...
Post Reply