Reputation: 141
so the problem is, I have a HTML form with checkboxes as an input-option. I want to save all the selected options as a string(!) in one variable.
I'm pretty sure the solution is a foreach-loop, but mine doesn't work. It only returns the last selected value.
How can I fix this?
HTML
<form action="" method="post">
<label>category:<br/>
one <input type="checkbox" name ="ber[]" value="one"><br/>
two <input type="checkbox" name ="ber[]" value="two"><br/>
thr <input type="checkbox" name ="ber[]" value="three"><br/>
fou <input type="checkbox" name ="ber[]" value="four"><br/>
</form>
PHP
foreach ($_POST['ber'] as $value) {
$ber = "$value. ', '"
}
Upvotes: 0
Views: 1356
Reputation: 54831
This is called "implode an array":
$ber = implode(',', $_POST['ber']);
echo $ber;
// or simply
echo implode(',', $_POST['ber']);
Upvotes: 7
Reputation: 5224
You need to concatenate.
$ber = ''
foreach ($_POST['ber'] as $value) {
$ber .= "$value. ', '"
}
With your current approach $ber =
overwrites the previous value.
A better solution though is implode
.
Upvotes: 2
Reputation: 2158
Just change your foreach loop with below foreach loop. You are getting ber
in POST
not category
. So you need to change $_POST['ber']
from $_POST['category']
.
$ber = '';
foreach ($_POST['ber'] as $value) {
$ber .= "$value. ', '"
}
Upvotes: 1
Reputation: 328
You will get the selected checkboxes value in POST array
<?php $_POST['ber']; ?>
Now If you want to assign this array to variable with comma separated
<?php $beer_value = implode(",", $_POST['ber']); ?>
Upvotes: 2