So, I have a couple of check boxes in my $_POST
array and I want to see if they are checked or not. Then I would like to print out the ones that are checked. How would I got about doing this?
Usually, the way we play with checkbox is, by using arrayed name like this:
<input type="checkbox" name="check[]" value="check 1" /> check<br />
<input type="checkbox" name="check[]" value="check 2" /> check<br />
<input type="checkbox" name="check[]" value="check 3" /> check<br />
This way, we can easily determine if someone checked our checkbox by using:
if( isset( $_POST['check'] ))
{
if( count( $_POST['check'] ) > 0 )
{
echo "checked value are: " . implode(", ", $_POST['check']);
}
}
This is mainly because browser doesn't send checkbox value that doesn't checked.
You can only print out the checked
checkboxes anyway, since the browser wont submit empty (unchecked) checkboxes:
foreach ($_POST as $key=>$val)
{
echo $key ." :: ".$val."<br/>";
}
This expands a little on @iHaveacomputer's answer.
Only checked checkboxes & radios are put into the $_POST
or $_GET
.
However, you can have an array of checkbox (or other types of input) so if you are using brackets in the names of your inputs, you should check to see if the value is an array or not.
foreach ($_POST as $input_name => $value_s)
{
if (is_array($value_s))
{
foreach ($value_s as $index => $value)
{
echo "$input_name[$index]::$value<br />";
// note that this literally prints the input_name, brackets, and index)
// using braces will just print the value
}
}
else
{
echo "$input_name::$value_s<br />";
}
}