Forms & PHP

Ask about general coding issues or problems here.

Moderators: egami, macek, gesf

Post Reply
New php-forum User
New php-forum User
Posts: 7
Joined: Sat Jul 19, 2014 11:24 pm

Sun Jul 20, 2014 9:29 pm

So I'm trying to keep the values in my form if it's not submitted successfully...however, I can't figure out how forms assign checkbox values. I'm a novice & working simple php code. I've tried assigning it to a variable standard and I've also tried assigning it to a variable as an array...still, all I get is the value of the last checkbox checked on the list. So now I'm trying to figure out how forms post checkbox values and if there's a way to get them into an array variable without having a unique name for each & posting a really long line to assign into an array variable...
Basically, I want to avoid this if I can:

Code: Select all

$reason=array($_POST["r1"], $_POST["r2"],.............);

php-forum Active User
php-forum Active User
Posts: 388
Joined: Thu Mar 15, 2012 3:59 pm

Mon Aug 04, 2014 9:28 am

I'm not entirely clear about your request, but hopefulyl these ideas will help.

1) As you've probably found out, if a checkbox isn't checked, then NOTHING is submitted. This is unlike other inputs like a 'text', where an empty string is submitted if nothing is entered in the box.

So for this code:

Code: Select all

<input type="checkbox" name="r1">
<input type="checkbox" name="r2">
If you check the second box (r2), then in $_POST you will have r2, but not r1, e.g. $_POST('r2') will exist, but $_POST('r1') will not.

2) You can create an array of inputs by adding [] to the name e.g.

Code: Select all

<input type="checkbox" name="r1[]" value="x">
<input type="checkbox" name="r1[]" value="y">
Note that both inputs have the same name (r1[]) and we have added a 'value' attribute.

Now if you check the second box, the value of $_POST('r1') will be an array, and the first element will have the value "y". If you check both, the array will contain the values ['x','y'].

Hope that helps. If I've misunderstood, please ask again :)


Post Reply