1

I have 42 checkboxes in my form as im programming a page where the user is choosing their interests.

By naming all the checkboxes "interest", is there any way of making an array of values?

Example:

<input  type="checkbox" name="interest" value="34" />
<input  type="checkbox" name="interest" value="19" />

//values in array
$interestArray[0] = 34;
$interestArray[1] = 19;
Jake
  • 3,326
  • 7
  • 39
  • 59
  • possible duplicate of [How to get form input array into PHP array](http://stackoverflow.com/questions/3314567/how-to-get-form-input-array-into-php-array) – jprofitt Feb 02 '12 at 19:02

3 Answers3

4

You're looking for this?

<form method="POST" action="">
<input  type="checkbox" name="interest[]" value="34" />
<input  type="checkbox" name="interest[]" value="19" />
<input  type="checkbox" name="interest[]" value="56" />

//values in array
$_POST['interest'][0] = 34;
$_POST['interest'][1] = 19;
$_POST['interest'][2] = 56;

Specifying an arrays key is optional in HTML. If you do not specify the keys, the array gets filled in the order the elements appear in the form.

From PHP manual: How do I create arrays in a HTML ?

Josh
  • 8,082
  • 5
  • 43
  • 41
  • 1
    How did I not know this before? Thanks for this! :) – spidEY Feb 02 '12 at 19:06
  • I have a habit of doing something like `name="interest[34]" value="34"` so the checkbox has a unique name. I think maybe once upon a time it broke validation otherwise, but it also makes it easier to find a specific checkbox with javascript. – Rob Feb 02 '12 at 19:08
2

Yes you can:

<input type="checkbox" name="formDoor[]" value="A" />Acorn Building<br />
<input type="checkbox" name="formDoor[]" value="B" />Brown Hall<br />

Then use the array:

<?php
  $aDoor = $_POST['formDoor'];
 .....
  }
?>
Jorge Zapata
  • 2,316
  • 1
  • 30
  • 57
1

Use PHP's array shortcut notation: name="interest[]". The [] tell PHP to treat multiple values as part of an array. Each checked checkbox will get its own entry in that array.

Marc B
  • 356,200
  • 43
  • 426
  • 500