Page 1 of 1

Loops inside form processing

Posted: Fri Sep 15, 2006 5:39 am
by mikeeeeeeey
Hi there,

I'm trying to get a loop to cycle through a series of check boxes. I've had no problem naming the checkboxes using a loop, but when I come to get the information out i.e. using $_POST['stuff'] I'm not sure where or how to put in the syntax for the loop variable.

Here's my code as it stands (not working):

Code: Select all

for ($i = 0; $i < $count; $i++)
	{
		if($_POST['sendTo' . $i] != NULL)
		{
			print($_POST['sendTo' . $i] . "<br/>");
		}
	}
The checkboxes are named 'sendTo1','sendTo2' etc etc., and it's just the $i and where to put it thats puzzling.

I'm sure it will only be a couple of characters I'm looking for, so any help would be much appreciated.

Thanks.

Posted: Fri Sep 15, 2006 5:50 am
by onion2k
On Topic: That code looks ok to me .. is it producing an error? What do you get if you do print_r($_POST); ?

Off Topic: Is there any reason why you're not using an array? By adding [] to the end of an HTML element name PHP automatically converts it to an array when you come to process it..

For example .. your HTML would be:

Code: Select all

<input type="checkbox" name="sendTo[]" value="person1"> Person 1<br>
<input type="checkbox" name="sendTo[]" value="person2"> Person 2<br>
<input type="checkbox" name="sendTo[]" value="person3"> Person 3<br>
<input type="checkbox" name="sendTo[]" value="person4"> Person 4<br>
Then your PHP to go through the checked checkboxes would be:

Code: Select all

if (is_array($_POST['sendTo'])) {
  foreach ($_POST['sendTo'] as $sendTo) {
    echo $sendTo;
  }
}
Of course, that assumes that $i in your script is only a counter and not significant in some other way.

Posted: Fri Sep 15, 2006 5:52 am
by volka
if you name your input element in a certain way, php will create an array from the values.

Code: Select all

<html>
	<head><title>...</title></head>
	<body>
<?php
if( isset($_POST['stuff']) && is_array($_POST['stuff']) ) {
	foreach($_POST['stuff'] as $index=>$value) {
		echo $index, ' -> ', $value, "<br />\n";
	}
	echo "<hr />\n";
}
?>
		<form method="post">
			<div>
				<input type="checkbox" name="stuff[0]" />0<br />
				<input type="checkbox" name="stuff[1]" />1<br />
				<input type="checkbox" name="stuff[2]" />2<br />
				<input type="checkbox" name="stuff[3]" />3<br />
				<input type="checkbox" name="stuff[4]" />4<br />
				<input type="submit" />
			</div>
		</form>
	</body>
</html>
edit: me=slowfinger/typer :(

Posted: Fri Sep 15, 2006 5:58 am
by mikeeeeeeey
Ahh I see.

Thanks guys, Arrays are pretty powerful, but different to control at first I suppose. Better get learning!