I have set up a small script to handle a page where I have three checkboxes.

The HTML for the checkboxes looks like this:

<input type="checkbox" value="Ex1" name="Check[]" />Ex1
<input type="checkbox" value="Ex2" name="Check[]" />Ex2
<input type="checkbox" value="Ex3" name="Check[]" />Ex3

And the PHP script for these:

if($_POST['Check'] == true){
foreach($_POST['Check'] as $value){
$check_msg .= "$value";
}
}

Now, what I want to do is insert "Ex1, Ex2" into my database, if the "Ex1" and "Ex2" checkboxes were checked. But the problem is, if I put ", " in front of "$value", it will insert ", Ex1, Ex2" to the database. But as I said, I want to insert it without the comma and space in the beginning... How could I do something like this? It doesn't matter if it's a foreach loop or another method, because I really don't know any other method to check which checkboxes were checked.

I have tried a few combinations but couldn't really get the results I wanted...

Thanks.

Accepted Answer

I always do that type of action with the following code;

foreach ( $_POST['Check'] as $key => $value ) {
  $check_msg .= ", {$value}";
}

$check_msg = substr($check_msg,2);

The last line just removes the ", " from the string you are building. Simpler and easier [IMHO] than checking the existing value of $check_msg every time you want to add the next item to it.

Written by Dave Rix
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki