0

I need to submit all my checkboxes on my page. I've got the following code to display the checkboxes:

foreach($categories as $category){
    $cat_name = $category->name;
    $cat_name = htmlspecialchars_decode($cat_name);
    $list_name = $network_name.' '.$cat_name;
    if (in_array($list_name, $list_names)) {
        $checked = 'checked';
    }else{
        $checked = '';
    }
    $output .= '<input type="hidden" name="subscribe[]" value="0">';
    $output .= '<input type="checkbox" name="subscribe[]" value="'.$list_name.'" '.$checked.'>';
    $output .= $list_name;
    $output .= '<br>';
}

Now I'm trying to process these with a foreach loop:

foreach($_POST['subscribe'] as $value){
    echo "it has a value of".$value;
}

This will only show me the checkboxed boxes but I also want to get the value of the non-checked boxes. Is there a way to do this?

user1048676
  • 9,756
  • 26
  • 83
  • 120
  • Values for checkbox(es) are only posted if they are checked. There are workarounds though. – George Aug 04 '15 at 15:55
  • possible duplicate of [Post the checkboxes that are unchecked](http://stackoverflow.com/questions/1809494/post-the-checkboxes-that-are-unchecked) – George Aug 04 '15 at 15:55

1 Answers1

2

The problem that you have is with the naming. Each loop has 2 elements, both named subscribe[] so when posted you cannot see if the 'checked' value has overwritten the 'unchecked' value, as you just have an array of elements.

You need a way to link the 2 elements together so that they have the same name, and the value if checked will overwrite the value if not checked.

Try incrementing an integer inside your loop and using it in both elements, so that each 'loop' has a unique element name (rather than each input).

Try this modification:

$i = 1;
foreach($categories as $category){

    $output .= '<input type="hidden" name="subscribe[$i]" value="0">';
    $output .= '<input type="checkbox" name="subscribe[$i]"  value="'.$list_name.'" '.$checked.'>';

    $i++;
}
MaggsWeb
  • 3,018
  • 1
  • 13
  • 23