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?

2
  • Values for checkbox(es) are only posted if they are checked. There are workarounds though. Commented Aug 4, 2015 at 15:55
  • possible duplicate of Post the checkboxes that are unchecked Commented Aug 4, 2015 at 15:55

1 Answer 1

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++;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.