Reputation: 367
I am new to PHP and am looking for some help with the following:
I have a large HTML form with various inputs, selects and textareas. On submit I pass all field values to another PHP page to create an email with them.
This works as intended for text inputs, radio buttons, selects, textareas etc. but not for checkboxes.
In the form I have multiple checkboxes that all look as follows using the same name:
<input type='checkbox' class='someClass' id='language1' name='language[]' value='de - German' />
<input type='checkbox' class='someClass' id='language2' name='language[]' value='en - English' />
<input type='checkbox' class='someClass' id='language3' name='language[]' value='fr - French' />
<!-- ... -->
On the PHP side I tried the following but if I then use $languages
for my email body it shows as blank (while all other fields appear correctly):
$languages = implode(',', $_POST['language[]']);
What I am trying to do is to save all values from the $_POST["language"]
array in one variable, separated with commas (and no comma at the end).
Can someone help me with this ?
Many thanks in advance
Upvotes: 2
Views: 9576
Reputation: 2378
HTML
<input type='checkbox' class='someClass' id='language1' name='language[]' value='1' />
<input type='checkbox' class='someClass' id='language2' name='language[]' value='2' />
<input type='checkbox' class='someClass' id='language3' name='language[]' value='3' />
<!-- ... -->
PHP
$language_ = array(1=>'de - German',2=>'en - English',3=>'fr - French');
if (!empty($_GET['language'])) {
foreach ($_GET['language'] as $l) {
$lan0 .= $language_[$l].', ';
}
echo rtrim($lan0,", ");
Upvotes: 0
Reputation: 116110
If you use anyname[]
in the form, PHP will translate it to an array, but without the []
in the name. So this should work:
$languages = implode(',', $_POST['language']);
Note that unchecked checkboxes are not posted, so if you check none, no value is posted and $_POST['language']
will not be set. You would have to check for that.
$languages = 'No languages selected';
if (isset($_POST['language'])){
$languages = implode(',', $_POST['language']);
}
Upvotes: 5