Checking the state of Checkboxes 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
tfneves
Forum Newbie
Posts: 2
Joined: Tue Sep 10, 2002 8:03 am

Checking the state of Checkboxes in PHP

Post by tfneves »

I have two forms. In form 1 the user checks checkboxes and in the second form. A PHP script checks the state of these checkboxes. The code is something like this:

Form 1:
----------
<input type="checkbox" name="product[][0]" value="">
<input type="text" name="product[][1]" value="">
<inpu type="text" name="product[][2]" value="">

Form 2:
----------
foreach($product as $value) {
if ($value[0] == "on") {
print "$value[1]\n";
print "$value[2]\n";
}
}

The values do get submitted to the form2 and I'm able to print out
$value[0]. It prints out as "on", but the if statement fails. If tried
trim($value[0]) it still doesn't work.

If anybody can give me help with this I will be extremely grateful.
Thanks
Tony
User avatar
Takuma
Forum Regular
Posts: 931
Joined: Sun Aug 04, 2002 10:24 am
Location: UK
Contact:

Post by Takuma »

Try using this....

Code: Select all

&lt;?php
foreach($_POST&#1111;"product"] as $value) { 
  if ($value&#1111;0] == "on") { 
    print $value&#1111;1]."\n"; 
    print $value&#1111;2]."\n"; 
  } 
}
?&gt;
Are you sure $value[1] and $value[2] have strings in them.?
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

Have you tried this in the code after submitting the form:

Code: Select all

echo '&lt;pre&gt;';
print_r($_POST&#1111;'product']);
echo '&lt;/pre&gt;';
if you do it you'll find that your array contains the following elements:

Code: Select all

$_POST&#1111;'product']&#1111;0]&#1111;0] = 'on'
$_POST&#1111;'product']&#1111;1]&#1111;1] = ''
$_POST&#1111;'product']&#1111;2]&#1111;2] = ''
So you need to adjust the way in which you are naming the form elements:

Code: Select all

&lt;input type="checkbox" name="product&#1111;0]&#1111;0]" value="on"&gt; 
&lt;input type="text" name="product&#1111;0]&#1111;1]" value=""&gt; 
&lt;input type="text" name="product&#1111;0]&#1111;2]" value=""&gt;
Then the if statement within the foreach loop will actually work. Also because the $value[0] element will only be set if the checkbox is checked change the loop to something like:

Code: Select all

foreach($_POST&#1111;'product'] as $value) { 
	if (isset($value&#1111;0])) { 
		echo $value&#1111;1].'&lt;br /&gt;'; 
		echo $value&#1111;2].'&lt;br /&gt;'; 
	} 
}
and you won't get undefined offset errors occuring.

(Change $_POST to $HTTP_POST_VARS if you are using PHP 4.0.6 or below.)

Mac
Post Reply